jueves, febrero 22, 2024
InicioSoftware Developmentfetch with Timeout

fetch with Timeout


A couple of years again I wrote a weblog publish about how write a fetch Promise that occasions 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 out there, let’s create a greater JavaScript perform for fetching with a timeout:

AbortSignal cases now characteristic a timeout choice to time the Promise out after a given quantity of milliseconds:

async perform 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,
  });

  // Await the fetch with a catch in case it is aborted which indicators an error
  const consequence = await _fetchPromise;
  return consequence;
};

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

Whereas previously the AbortSignal would come from an AbortController, now you can use AbortSignal.timeout to create the sign.

In the mean time, nevertheless, solely edge browser variations assist AbortSignal.timeout. A lot like the unique perform, an alternate perform may 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
  attempt {
    const consequence = await _fetchPromise;
    clearTimeout(timer);
    return consequence;
  } 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 have now 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.


RELATED ARTICLES

DEJA UNA RESPUESTA

Por favor ingrese su comentario!
Por favor ingrese su nombre aquí

Most Popular

Recent Comments