Home > Web Front-end > JS Tutorial > How to use Promise.race to add timeout to fetch calls

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

Mary-Kate Olsen
Release: 2024-12-01 18:18:11
Original
284 people have browsed it

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);
Copy after login

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);
Copy after login

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);
Copy after login

The above is the detailed content of How to use Promise.race to add timeout to fetch calls. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template