I have a piece of code in which multiple promises are being handled using Promise.all, but one of the promise isn’t resolving or rejecting but throwing error. Now my question is how to handle this error inside promise.all.
Please note, promises are coming from 3rd party module (node_modules) so i cannot change the code inside the promises, but can only handle the error.
a implementation of above question is
try {
const a = await Promise.all([
Promise.resolve(1),
func1()
// Promise.reject(4),
]);
console.log(a);
} catch (e) {
console.log("caught", e); // no error caught
}
// suppose func1 is some function exported by 3rd party package
async function func1() {
return await new Promise((rs, rj) => {
return setTimeout(() => {
throw new Error("error");
}, 1000);
});
}
Tried many ways like
func1().catch(e => e)
func2(){
try{ func1() }catch(err){ throw err }
}
2
Answers
You should use
reject
callback in a promise constructor explicitly, otherwise your error is thrown in another JS macrotask, not affecting the promise.Given that an async function rejects a promise properly
Promise.all
works as expected:The code in the post launches a timeout that throws an error at global file level rather than in code that executes within a
try/catch
block the promise job handler puts aroundfulfilled
,rejected
, orfinally
handler code when executing them to see what they do and return.An error thrown at file level could be monitored by a
window.onerror
listener. You might be able to detect that and use it to reject a promise that could also be resolved by the problematic promise provider if it works. Then use aPromise.race
construct to see which happens first – an error is thrown at file level, or thePromise.all
becomes settled.This is not an ongoing fix – the approach is assuming the error is thrown by the dodgy promise provider, but not proven.
As a code outline: