cachaito
9/27/2017 - 12:05 PM

Promise.race()

Promise.race is useful if you want to run multiple promises, and either…

  1. do something with the first successful result that comes in (in case one of the promises fulfills), or
  2. do something as soon as one of the promises rejects.

That is, if one of the promises rejects, you want to preserve that rejection to treat the error case separately. The following second example does exactly that.

// first example - load document and if this operation will be slower than 1000ms run second promise
function timeout(ms) {
  return new Promise((resolve, reject) => {
    setTimeout(reject, ms);
  })
}

Promise.race([readFilePromise('index.html'), timeout(1000)])
.then(data => console.log(data))
.catch(e => console.log("Timed out after 1 second"));

//second example
try {
  const result = await Promise.race([
    performHeavyComputation(),
    rejectAfterTimeout(2000),
  ]);
  renderResult(result);
} catch (error) {
  renderError(error);
}