Home > Software design >  Using multiple await()
Using multiple await()

Time:02-18

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) ?

CodePudding user response:

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...");

})();

CodePudding user response:

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)
})()

CodePudding user response:

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()
  • Related