Monday, January 16, 2023
HomeProgrammingfetch with Timeout

fetch with Timeout


A couple of years again I wrote a weblog publish about how write a fetch Promise that instances out. The perform was efficient however the code wasn’t nice, principally 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 similar to 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 alerts an error
  attempt {
    const end result = await _fetchPromise;
    clearTimeout(timer);
    return end result;
  } catch (e) {
    clearTimeout(timer);
    throw e;
  }
};

// Utilization
attempt {
  const impatientFetch = await fetchWithTimeout('/', {}, 2000);
}
catch(e) {
  console.log("fetch probably 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 glorious seeing AbortController, AbortSignal, and fetch evolve to make async requests extra controllable with out drastically altering the API.

  • 6 Things You Didn’t Know About Firefox OS

    Firefox OS is everywhere in the tech information and for good motive:  Mozilla’s lastly given internet builders the platform that they should create apps the best way they have been creating them for years — with CSS, HTML, and JavaScript.  Firefox OS has been quickly enhancing…

  • Write Better JavaScript with Promises

    You’ve got in all probability heard the discuss across the water cooler about how guarantees are the longer term. The entire cool children are utilizing them, however you do not see what makes them so particular. Cannot you simply use a callback? What is the massive deal? On this article, we’ll…

  • Drag. Drop. Lock.
  • jQuery Link Nudge Plugin

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments