'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) ?
Solution 1:[1]
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)
})()
Solution 2:[2]
Promise.race() or Promise.any()
- If one of the promises's status changed whatever
rejectedorfulfilled, you can usePromise.race() - If you want one of the promises to be
fulfilled, you should usePromise.any()
Solution 3:[3]
Promise.any can continue to execute other code if any One Promise will resolved.
let i = 1;
const newPromise = () => {
return new Promise((resolve) => {
setTimeout(() => {
console.log(`promise${i++} resolved`);
resolve(true);
}, Math.random() * 1000)
});
}
(async() => {
await Promise.any([newPromise(), newPromise()]);
console.log("Code will executes if any promise resolved");
})()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | NeNaD |
| Solution 2 | Peter Csala |
| Solution 3 |
