How to use Promise.race to add timeout to fetch calls
websilvercraft
Posted on November 19, 2024
The fetch API is super handy for making network requests, but it doesn't come with a built-in timeout feature. This means your app might hang indefinitely if the network is slow or the server isn't responding.
Luckily JavaScript is a versatile language, centered on event driven programming, providing a set of utility function grouped in the Promise object. Using Promise.race method, we can create a timeout mechanism for our fetch calls. This way, we can keep our applications responsive, even when things don't go as planned with the network.
So, I'll walk you through how to implement this timeout using Promise.race. We'll start with a simple fetch example and then enhance it by adding a timeout. I'll also share a real-world scenario where we deal with CSRF tokens to show you how this method works in a secure context.
Let's assume we have this:
// Prepare fetch options
const options = {
method: method,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-CSRF-TOKEN': csrfToken
},
body: JSON.stringify({items})
};
// Make the fetch request
const response = await fetch(fetchUrl, options);
If we want to add a timeout mechanism to fetch, we can create a promise with a timeout that triggers a reject. The promise make use of the Promise.race, to run multiple promises and when one finishes with reject or resolve, stops the all the rest.
// Timeout mechanism for fetch
const fetchWithTimeout = (url, options, timeout = 5000) => {
return Promise.race([
fetch(url, options),
new Promise((_, reject) => setTimeout(() => reject(new Error('Request timed out')), timeout))
]);
};
// Make the fetch request
const response = await fetchWithTimeout(fetchUrl, options);
Here is a real world example with CSRF tokens
// Validate CSRF token
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;
if (!csrfToken) {
throw new Error('CSRF token not found in the document.');
}
// Prepare fetch options
const options = {
method: method,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-CSRF-TOKEN': csrfToken
},
body: JSON.stringify({items})
};
// Timeout mechanism for fetch
const fetchWithTimeout = (url, options, timeout = 5000) => {
return Promise.race([
fetch(url, options),
new Promise((_, reject) => setTimeout(() => reject(new Error('Request timed out')), timeout))
]);
};
// Make the fetch request
const response = await fetchWithTimeout(fetchUrl, options);
π Interested to learn more π οΈπ€π»? Then don't forget to π¬βοΈ, π
π If you are interested in learning more about programming, π οΈ building applications, or in general about AI π€ and tech π», you can subscribe to my newsletter at websilvercraft.substack.com βοΈ to get the posts delivered directly to you as soon as I publish them! π¬
β β β β β β β β β β ππππ
β β β β β β β β πππππππππππ
β β ππππππππππππππππππππ
ππππππππππππππππππππππππππππππππ
Posted on November 19, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.