Handling timeouts with the Fetch API is an important aspect of building robust web applications. By default, the Fetch API does not support timeouts directly, which means that if a request takes too long, it will hang indefinitely unless explicitly managed. In this response, we will explore various methods to implement timeouts, best practices, and common pitfalls to avoid.
To implement a timeout with Fetch, we can use the Promise.race method, which allows us to race the fetch request against a timeout promise. This way, if the fetch request does not complete within the specified time, we can reject it and handle the timeout appropriately.
Here’s a simple example of how to implement a timeout using Fetch:
function fetchWithTimeout(url, options = {}, timeout = 5000) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error('Request timed out'));
}, timeout);
fetch(url, options)
.then(response => {
clearTimeout(timer);
if (!response.ok) {
reject(new Error('Network response was not ok'));
}
return response.json();
})
.then(data => resolve(data))
.catch(err => {
clearTimeout(timer);
reject(err);
});
});
}
// Usage
fetchWithTimeout('https://api.example.com/data', {}, 3000)
.then(data => console.log(data))
.catch(err => console.error(err.message));
Here’s an example of how to use AbortController to implement a timeout:
function fetchWithAbort(url, options = {}, timeout = 5000) {
const controller = new AbortController();
const signal = controller.signal;
const timeoutId = setTimeout(() => {
controller.abort();
}, timeout);
return fetch(url, { ...options, signal })
.then(response => {
clearTimeout(timeoutId);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.catch(err => {
if (err.name === 'AbortError') {
throw new Error('Request timed out');
}
throw err;
});
}
// Usage
fetchWithAbort('https://api.example.com/data', {}, 3000)
.then(data => console.log(data))
.catch(err => console.error(err.message));
Implementing timeouts with the Fetch API is essential for creating responsive web applications. By using techniques such as Promise.race and AbortController, developers can effectively manage request timeouts. Following best practices and avoiding common mistakes will lead to a more robust and user-friendly application.