0

I get UnhandledPromiseRejection when i run the following code on node.js v17.1.0. The "awaited" rejectAfter100ms promise is not catched neither by the surrounding "trycatch" inside the async function nor by "then" method on the returned promise.

Why such behaviour? Any explanation coming from the specification?

const asyncFunc = async () => {
  const resolveAfter2000ms = new Promise((resolve) => {
    setTimeout(resolve, 2000);
  });
  const rejectAfter100ms = new Promise((_, reject) => {
    setTimeout(reject, 100);
  });

  try {
    await resolveAfter2000ms;
    await rejectAfter100ms;
  } catch (error) {
    console.log('error catched inside async');
  }
};

asyncFunc().catch(() => console.log('error catched outside async'));
sage agat
  • 93
  • 1
  • 7
  • Either do it sequentially (getting the error after 2100ms), or use `Promise.all` (getting the error after 100ms). Never start off multiple operations at once but proceed to `await` them independently. – Bergi Nov 27 '21 at 21:50

0 Answers0