Create Javascript Fetch(), But with Timeout
Table of contents
Hello Devs,
We want to fetch data from a particular URL and show it in the console. But if the URL is taking so long or taking longer time than the user-specified time, It will get automatically aborted.
So that is the problem statement, let's see how to conquer it.
Goal:
We want a function that accepts a "URL" & "Time" as a Parameter and like fetch(), and returns a Promise.
const fetchWithTimeOut = (url, time) => { return new Promise((resolve, reject) => { }); };
Then we call the normal fetch call, which we usually do most of the time .
const fetchWithTimeOut = (url, time) = >{ return new Promise((resolve, reject) = >{ // Writing normal fetch method fetch(url).then((resp) = >{ clearTimeout(timeId); return resp.json(); }).then((data) = >{ resolve(data); }). catch((e) = >{ reject(e); }); }); };
But you will ask me, It's okay but how we will control it on the basis of time ? Here comes the "Hero of the movie"
AbortController();
The
AbortController
is used to provide a way to abort a network request created using thefetch
.Creation of the
AbortController
instance:const controller = new AbortController();
Here, an
AbortController
instance is created. AnAbortController
is an object that allows you to associate anAbortSignal
with it, which can be used to send an abort signal to one or more DOM requests, such as afetch
request.const signal = controller.signal;
The
signal
property of theAbortController
object is used to get the associatedAbortSignal
. TheAbortSignal
is a signal object that can be used to abort one or more DOM requests, such as afetch
request.fetch(url, { signal }) .then((resp) => { clearTimeout(timeId); return resp.json(); }) .then((data) => { resolve(data); }) .catch((e) => { reject(e); });
When making a
fetch
request, you can pass theAbortSignal
as an option in the request configuration. This associates theAbortController
with the network request. If an abort signal is sent to theAbortController
(e.g., by callingcontroller.abort()
), it will cancel the network request, and any pending promises related to that request will be rejected.A timer is set using, which will call
controller.abort()
after a specifiedtime
interval. If the network request doesn't complete within this timeout period, thecontroller.abort()
function is called, which sends an abort signal to the associatedfetch
request. This effectively cancels the request.timeId = setTimeout(() => { controller.abort(); }, time);
Full Code :
const fetchWithTimeOut = (url, time) => {
return new Promise((resolve, reject) => {
let timeId;
const controller = new AbortController();
const signal = controller.signal;
fetch(url, { signal })
.then((resp) => {
clearTimeout(timeId);
return resp.json();
})
.then((data) => {
resolve(data);
})
.catch((e) => {
reject(e);
});
timeId = setTimeout(() => {
controller.abort();
}, time);
});
};
fetchWithTimeOut("https://jsonplaceholder.typicode.com/todos/1", 100)
.then((resp) => {
console.log(resp);
})
.catch((e) => {
console.log(e);
});
Subscribe to my newsletter
Read articles from Raj directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by