Friday, January 20, 2023
HomeSoftware Developmentfetch with Timeout

fetch with Timeout


A number of years again I wrote a weblog put up about how write a fetch Promise that instances out. The perform was efficient however the code wasn’t nice, largely as a result of AbortController , which lets you cancel a fetch Promise, didn’t but exist. With AbortController and AbortSignal accessible, let’s create a greater JavaScript perform for fetching with a timeout:

Very like the unique perform, we’ll use setTimeout to time to the cancellation however we’ll use the sign with the fetch request:

async perform fetchWithTimeout(url, opts = {}, timeout = 5000) {
  // Create the AbortController occasion, get AbortSignal
  const abortController = new AbortController();
  const { sign } = abortController;

  // Make the fetch request
  const _fetchPromise = fetch(url, {
    ...opts,
    sign,
  });

  // Begin the timer
  const timer = setTimeout(() => abortController.abort(), timeout);

  // Await the fetch with a catch in case it is aborted which indicators an error
  strive {
    const consequence = await _fetchPromise;
    clearTimeout(timer);
    return consequence;
  } catch (e) {
    clearTimeout(timer);
    throw e;
  }
};

// Utilization
strive {
  const impatientFetch = await fetchWithTimeout('/', {}, 2000);
}
catch(e) {
  console.log("fetch presumably canceled!", e);
}

The JavaScript code above is far cleaner now that we’ve got a correct API to cancel fetch Promise calls. Attaching the sign to the fetch request permits us to make use of a setTimeout with abort to cancel the request after a given period of time.

It has been wonderful seeing AbortController, AbortSignal, and fetch evolve to make async requests extra controllable with out drastically altering the API.

  • 5 Awesome New Mozilla Technologies You’ve Never Heard Of

    My journey to Mozilla Summit 2013 was unbelievable.  I’ve spent a lot time specializing in my undertaking that I had overlooked the entire nice work Mozillians had been placing out.  MozSummit offered the proper reminder of how sensible my colleagues are and the way a lot…

  • Tips for Starting with Bitcoin and Cryptocurrencies

    One of the rewarding experiences of my life, each financially and logically, has been shopping for and managing cryptocurrencies like Bitcoin, Litecoin, Ethereum. Like studying some other new tech, I made rookie errors alongside the way in which, however realized some finest practices alongside the way in which. Try…



Supply hyperlink
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments