I have some issues to handle multiple rejections in "parallel".
How to handle rejection in a async function when we "await in parallel".
Here an example :
function in_2_sec(number) {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject('Error ' + number);
}, 2000);
})
}
async function f1() {
try {
let a = in_2_sec(3);
let b = in_2_sec(30);
return await a + await b; // awaiting in "parallel"
} catch(err) {
console.log('Error', err);
return false;
}
}
async function f2() {
try {
let a = await Promise.all([in_2_sec(3), in_2_sec(30)]);
return a[0] + a[1];
} catch(err) {
console.log('Error', err);
return false;
}
}
// f1().then(console.log) // UnhandledPromiseRejectionWarning
// f2().then(console.log) // Nice
f1()
create a UnhandledPromiseRejectionWarning
in node, because the second rejection (b) is not handled. f2()
works perfectly, Promise.all()
do the trick, but how to make a f2()
with only async/await syntax, without Promise.all()
?
Promise. all is all or nothing. It resolves once all promises in the array resolve, or reject as soon as one of them rejects. In other words, it either resolves with an array of all resolved values, or rejects with a single error.
Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand.
f2()
works perfectly,Promise.all()
do the trick, but how to make af2()
with only async/await syntax, withoutPromise.all()
?
Not at all. Use Promise.all
! This is what it was made for. Don't think of async
/await
of replacing promises - you still are using them, it's only syntactic sugar for then
calls. There is no syntactic replacement for Promise.all
.
Of course it's also possible to re-implement the behaviour of Promise.all
yourself (relying on the Promise
constructor and .then
primitives), but you really don't want to do that (there are too many pitfalls).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With