DEV Community

websilvercraft
websilvercraft

Posted on

How to use Promise.race to add timeout to fetch calls

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

šŸš€ 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! šŸ“¬
ā €ā €ā € ā €ā €ā €ā € ā €ā € ā €šŸ‘†šŸ‘†šŸ‘†šŸ‘†
ā €ā €ā €ā €ā €ā €ā €ā € šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†
ā € ā € šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†
šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†šŸ‘†

Top comments (0)