Promise.race timeout

Promise.race timeout

To implement a timeout using the Promise.race method, you can use a promise that rejects after a specified time period. Here's an example of how you might do this:

function timeout(ms) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject(new Error("timeout"));
    }, ms);
  });
}

const p1 = fetch("http://example.com/resource1");
const p2 = fetch("http://example.com/resource2");

Promise.race([p1, p2, timeout(1000)]).then(
  value => {
    console.log(value); // either the response from resource1 or resource2
  },
  error => {
    console.log(error); // "timeout"
  }
);

In this example, we are using the timeout function to create a promise that will reject with an error after a specified time period (in this case, 1000 milliseconds). The timeout function returns a new promise that is rejected after the specified time period using the setTimeout function.

We are then using the Promise.race method to wait for either p1 or p2 to resolve, or for the timeout promise to reject. If either p1 or p2 resolves before the timeout, the then callback function is called with the resolved value. If the timeout promise rejects before either p1 or p2 resolves, the then callback function is called with the error.


  • Date: