fetch with Timeout


A couple of years again I wrote a weblog put up about how write a fetch Promise that occasions out. The serve as used to be efficient however the code wasn’t nice, most commonly as a result of AbortController , which lets you cancel a fetch Promise, didn’t but exist. With AbortController and AbortSignal to be had, let’s create a greater JavaScript serve as for fetching with a timeout:

AbortSignal circumstances now function a timeout approach to time the Promise out after a given quantity of milliseconds:

async serve as fetchWithTimeout(url, opts = {}, timeout = 5000) {
  // Create a sign with timeout
  const sign = AbortSignal.timeout(timeout);

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

  // Watch for the fetch with a catch in case it is aborted which indicators an error
  const consequence = anticipate _fetchPromise;
  go back consequence;
};

// Utilization
take a look at {
  const impatientFetch = anticipate fetchWithTimeout('/', {}, 2000);
}
catch(e) {
  console.log("fetch most likely canceled!", e);
}

Whilst previously the AbortSignal would come from an AbortController, you’ll now use AbortSignal.timeout to create the sign.

At the present time, on the other hand, simplest edge browser variations enhance AbortSignal.timeout. Such a lot like the unique serve as, another serve as may use setTimeout to time to the cancellation however we will use the sign with the fetch request:

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

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

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

  // Watch for the fetch with a catch in case it is aborted which indicators an error
  take a look at {
    const consequence = anticipate _fetchPromise;
    clearTimeout(timer);
    go back consequence;
  } catch (e) {
    clearTimeout(timer);
    throw e;
  }
};

// Utilization
take a look at {
  const impatientFetch = anticipate fetchWithTimeout('/', {}, 2000);
}
catch(e) {
  console.log("fetch most likely canceled!", e);
}

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

It is been superb seeing AbortController, AbortSignal, and fetch evolve to make async requests extra controllable with out tremendously converting the API.


Like this post? Please share to your friends:
Leave a Reply

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: