I have two promises without catch blocks in the beginning and I'm doing await on both of them later with catch
blocks. Second promise reject
s before first promise resolve
s. So, while I'm still await
ing on the first promise, second promise is reject
ed and since I have not attached the catch
yet, it crashes the server with UnhandledPromiseRejection
.
Is there a way to make p2's reject
propagate to await p2
, like it does in case when p2 resolve
s?
PS: I cannot attach the catch in the beginning itself.
Adding the code below for reference. In stackoverflow it works fine for some reason, but when run from local, the server crashes.
async function main() {
console.log("starting");
let p1 = new Promise((resolve, reject) => {
console.log('p1 sleeping');
setTimeout(function() {
console.log('p1 awake');
resolve('p1 resolved');
}, 5000);
});
let p2 = new Promise((resolve, reject) => {
console.log('p2 sleeping');
setTimeout(function() {
console.log('p2 awake');
reject('p2 rejected'); //IMPORTANT
}, 1000);
});
//Below line takes 5 seconds to execute.
//But p2 throws error after 1 second because no .catch() is attached to it yet.
let out1 = await p1.catch(e => {
console.log('p1 errored', e)
});
console.log('p1 output', out1);
let out2 = await p2.catch(e => {
console.log('p2 errored', e)
});
console.log('p2 output', out2);
}
main().then(() => {
console.log('stopped')
});
Comments
Post a Comment