liveBook · Manning

Promise.race

As explained in Secrets of the JavaScript Ninja, Third Edition

Promise.race is a static Promise method that creates a promise settled according to the first supplied promise to settle.

Promise.race takes an array of promises and returns one promise that settles with the first input to settle, whether fulfilled or rejected. section 8.1.3

Listing 8.5 Using Promise.race to enforce a timeout
const fetchController = new AbortController(); #A
 
const fetchPromise = fetch("https://httpbin.org/delay/2", { #B
  signal: fetchController.signal, #B
}).then((response) => { #B
  if (!response.ok) { #B
    throw new Error(`Status code ${response.status}`); #B
  } #B
  return response.json(); #B
});
 
const timeoutPromise = new Promise((_, reject) => #C
  setTimeout(() => { #C
    fetchController.abort(); #C
    reject(new Error("Request timeout"));
  }, 1_000), #C
); #C
 
Promise.race([fetchPromise, timeoutPromise]) #D
  .then((result) => {
    console.log(result);
  })
  .catch((reason) => {
    console.error(`Request failed: ${reason}`);
  });

A timeout promise can race a fetch. The example uses AbortController to abort the fetch when the timer fires; racing alone would not stop the losing request. section 8.1.3

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines first-settled behavior and demonstrates a fetch timeout with explicit request cancellation.
Examples
Demonstrates racing a delayed fetch against a one-second timer and aborting the request on timeout.
What it assumes
Assumes familiarity with promises and their fulfilled, rejected, and settled states.
What you can do after
Apply Promise.race to enforce a timeout, using AbortController when the losing fetch should be canceled.
How it connects
Connects promises with fetch and AbortController, and contrasts Promise.any as a first-fulfilled alternative.

Also explained in

Compare how 2 books explain Promise.race →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.