Maksim
Maksim

Reputation: 1

Why block catch() doesn't catch error, when I use "for await" cycle

The block catch(err){} in promiseAll function doesn't catch error.

const promiseAll = async (promises) => {
  const result = [];

  try {
    for await (let element of promises) {
      result.push(element);
    }
  } catch (err) {
    throw err;
  }

  return result;
};

const result = promiseAll([
  Promise.resolve(1),
  new Promise((resolve) => {
    setTimeout(() => {
      resolve(3);
    }, 3000);
  }),
  Promise.resolve(2),
  Promise.reject(2),
  new Promise((resolve) => {
    setTimeout(() => {
      resolve(3);
    }, 1000);
  }),
]);

result
  .then((data) => console.log("Data", data))
  .catch((err) => console.log("err", err));

The block catch(err){} in promiseAll function doesn't catch error. For me interesting why I can't catch the error in block catch. What is the solution ?

Upvotes: 0

Views: 51

Answers (1)

Keith
Keith

Reputation: 24221

Because you have not attached any error handling catch callbacks to your error, and you allow extra event loops (ticks) to fire, Chrome will see this as an unhanded promise rejection error.

One solution to just simply attach a catch callback to all the elements before awaiting them.

Example below, the only downside is that it will only report the first error it finds, but you could handle that issue too if it required.

const promiseAll = async (promises) => {
  const result = [];
  //were awaiting promises, let attach dummy catch
  //so that next tick doesn't detect error as unhandled.
  for (let element of promises) element.catch(e => {});
  //Don't worry the error we just swallowed above
  //will resurface during the await
  for (let element of promises) {
    result.push(await element);
  }
  return result;
};

const result = promiseAll([
  Promise.resolve(1),
  new Promise((resolve) => {
    setTimeout(() => {
      resolve(3);
    }, 3000);
  }),
  Promise.resolve(2),
  Promise.reject(2),
  new Promise((resolve) => {
    setTimeout(() => {
      resolve(3);
    }, 1000);
  }),
]);

result
  .then((data) => console.log("Data", data))
  .catch((err) => console.log("err", err));

Upvotes: 1

Related Questions