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)

Cloudinary image

Zoom pan, gen fill, restore, overlay, upscale, crop, resize...

Chain advanced transformations through a set of image and video APIs while optimizing assets by 90%.

Explore

πŸ‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay