Let’s suppose I have 5 promises (A,B,C,D,E) that I want to fire in parallel. Then I need to wait for any of (A,B) AND any of (C,D) AND E before executing a code.
My actual approach was something like:
let promises_AB = new Array();
let promises_CD = new Array();
let promises_E = new Array();
promises_AB.push(promiseA());
promises_AB.push(promiseB());
promises_CD.push(promiseC());
promises_CD.push(promiseD());
promises_E.push(promiseE());
//Promises on top will execute in parallel
try{
let res = await Promise.any(promises_AB);
//Do code after getting AB
} catch (e){
//error handler
}
try{
let res = await Promise.any(promises_CD);
//Do code after getting CD
} catch (e){
//error handler
}
try{
let res = await Promise.any(promises_E);
//Do code after getting E
} catch (e){
//error handler
}
//DO CODE HERE which executes after promises A,B,C,D,E
The problem here is that since promises CD can be faster than AB, since I await first for AB, if an error occurs in CD before AB returns I don’t have yet the try/catch for CD and I get a unhandled promise rejection.
The only (bad) solution I see is a big try/catch around all three awaits but I wanted to differentiate the error handler per promise group.
3
Answers
You can "merge" the processing using
Promise.all
:Use
Promise.all()
to wait for eachPromise.any()
in parallel.You could use
Promise.all()
to group the promises:Alternatively, you could use
Promise.allSettled()
if you want to wait for all the promises to settle, regardless of whether they were fulfilled or rejected. This would allow you to differentiate the error handling per promise group and handle cases where some promises are rejected, and others are fulfilled:See recent relevant video Dangers of Promise.all() by t3dotgg@