0

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 rejects before first promise resolves. So, while I'm still awaiting on the first promise, second promise is rejected 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 resolves?

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')
});
Vasudev
  • 803
  • 1
  • 7
  • 16
  • "*I'm doing `await` on them later*" - don't do that. For precisely the reason you found out. "*I cannot attach the catch in the beginning itself.*" - yes you could, what's stopping you? – Bergi Mar 24 '22 at 20:21

1 Answers1

0

If you run your code in Stack Overflow console, it still throwns an UnhandledPromiseRejection because you are not handling the Promise rejection (you can se the error on your browser DevTools).

You should try using Promise.all or handle each Promise result with then() and catch().

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Danilo
  • 1
  • 1