How to catch a rejected promise in a new expression node v14.4.0 "for await ... of"

151 Views Asked by At

I emulated 3 promises - two resolved, one rejected, wrapped a try-catch function, but I still get warnings in the console: (node: 4159) UnhandledPromiseRejectionWarning: Unhandled promise rejection.

    const emulate = (id, ms) =>
      new Promise((resolve, reject) => {
        if (ms > 1500) reject(id);
        setTimeout(() => {
          resolve(id);
        }, ms);
      });

    const promises = [
      emulate(1, 500),
      emulate(2, 1000),
      emulate(3, 2000)
    ];

    async function stepByStepResolve() {
      try {
        for await (const promise of promises)
          console.log(promise);
      } catch (e) {
        console.log('Err:', e);
      }
    }

    stepByStepResolve();
1

There are 1 best solutions below

0
On

When you call emulate(3, 2000) in the promises array, a promise is created, and will get rejected on the next phase of the event loop, except if you are listening to it and handling it, before that. Now, in the for loop, you are listening to all 3 promises in order, and since emulate(3, 2000) is being listened to last, it would have already been rejected by the time you iterate to it.

I can suggest two solutions to this:

Solution 1: Simply place emulate(3, 2000) as the first element in the array

let promises = [
  emulate(3, 2000),
  emulate(1, 500),
  emulate(2, 1000),
];

This will allow it to be listened to, and caught before it gets rejected.

Solution 2 (this is more of a suggestion): use a generator instead of an array, like this:

function* promisesGenerator() {
  yield emulate(3, 2000);
  yield emulate(1, 500);
  yield emulate(2, 1000);
}

async function stepByStepResolve() {
  try {
    for await (const promise of promisesGenerator())
      console.log(promise);
  } catch (e) {
    console.log('Err:', e);
  }
}

stepByStepResolve();

This will keep the promises from being created before the for loop, and will the be created one by one as you iterate through the generator.