Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 3975

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T07:41:04+00:00 2024-11-26T07:41:04+00:00

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

  • 61k

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! 📬
⠀⠀⠀ ⠀⠀⠀⠀ ⠀⠀ ⠀👆👆👆👆
⠀⠀⠀⠀⠀⠀⠀⠀ 👆👆👆👆👆👆👆👆👆👆👆
⠀ ⠀ 👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆
👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆👆

beginnersjavascriptprogrammingwebdev
  • 0 0 Answers
  • 2 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.