Well, I might be new to the community, but I would like to share what I think. Since, fetch Api does not have its own timeout feature we need to use other JavaScript features like aborting signals or promises. But both of these are used according to specific scenarios. Here,
Using Abort Signal:
const Timeout_with_Abort = (url, options, timeout = 3000) => {
const controller = new AbortController();
const signal = controller.signal;
const request_timeout = setTimeout(() => controller.abort(), timeout);
return fetch(url, { ...options, signal })
.then(response => {
clearTimeout(request_timeout);
return response;
})
.catch(error => {
clearTimeout(request_timeout);
throw error;
});
};
However, using this method has its on pros and cons.
- Abort Signal is not only used for implementing request timeouts but
to end the request at any time due to any reason, however, they might
not have support in older versions.
On the other hand I use promises because it seems easy for most software engineers including myself:
Using Promises
const Timeout_with_Promises= (url, options, timeout = 3000) => {
return new Promise((resolve, reject) => {
const request_timeout= setTimeout(() => reject(new Error('Request timed out')), timeout);
fetch(url, options)
.then(response => {
clearTimeout(request_timeout);
resolve(response);
})
.catch(error => {
clearTimeout(request_timeout);
reject(error);
});
});
};
Pros for this approach is simply this that
- This method is supported across all browser versions
- Fairly easy for most developers now a days
In the end, I can just say that even though using abort signals is a more modern approach, but it mostly depends on your implementation case.
fetch(url, { signal: AbortSignal.timeout(5000) })
a good option nowadays?" - yes it is. Not sure what kind of edit to this answer you would expect?new AbortController
, etc.) 3) the ending small-text paragraph. I can do the edit, but I wanted to be sure the simple one-line solution is really ok nowadays.