Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
Using multiple await()

Suppose I have two promises. Normally, the code cannot execute until all these promise are finished. In my code, suppose I have promise1 and promise 2 then I have await promise1 and await promise2. My code won't execute until both these promise are finished. However what I need is that if one of these two is finished then the code can execute and then we can ignore the other one. That is possible because the code only needs one of these awaits to succeed. Is this possible to implement in javascript (nodejs) ?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Promise.any is what you're looking for:

Promise.any() takes an iterable of Promise objects. It returns a single promise that resolves as soon as any of the promises in the iterable fulfills, with the value of the fulfilled promise. If no promises in the iterable fulfill (if all of the given promises are rejected), then the returned promise is rejected with an AggregateError, a new subclass of Error that groups together individual errors.

Example:

const randomDelay = (num) => new Promise((resolve) => setTimeout(() => {
  console.log(`${num} is done now`);
  resolve(`Random Delay ${num} has finished`);
}, Math.random() * 1000 * 10));

(async() => {
  console.log("Starting...");
  const result = await Promise.any(new Array(5).fill(0).map((_, index) => randomDelay(index)));
  console.log(result);
  console.log("Continuing...");

})();

about 4 years ago · Juan Pablo Isaza Report

0

You can use Promise.any() function. You can pass an array of Promises as an input, and it will resolve as soon as first Promise resolves.

(async() => {
  let promises = [];
  promises.push(new Promise((resolve) => setTimeout(resolve, 100, 'quick')))
  promises.push(new Promise((resolve) => setTimeout(resolve, 500, 'slow')))

  const result = await Promise.any(promises);
  console.log(result)
})()

about 4 years ago · Juan Pablo Isaza Report

0

Promise.race() or Promise.any()

  • If one of the promises's status changed whatever rejected or fulfilled, you can use Promise.race()
  • If you want one of the promises to be fulfilled, you should use Promise.any()
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!