简体   繁体   中英

Handling errors in Promise.all - promise rejection + type error

I have few Promise.all functions:

const fn = async () => {
   await Promise.all(first());
   await Promise.all(second());
   await Promise.all(third());
}

first , second and third functions looks almost the same together.

first function:

const first = async () => {
   const oldUsers = await User.find(...);

   return Array.isArray(oldUsers) ? oldUsers.map(async (user) => {
      await User.updateOne({ _id: user._id }, { ... });

      await transporter.sendMail(sendMail(user));
   }) : [];
};

My problem:

When starting the app and calling fn function, only first Promise.all is success (user is updated and mail is sent), but the second and third is not even called.

In console, I got error:

UnhandledPromiseRejectionWarning: TypeError: undefined is not a function

Im struggling with it whole day , what should I do, so the all three Promise.all are finished successfully? Looking for help, thank you in advance.

Your problem is that Promise.all takes an array of promises, but your first() function is async and therefore returns a promise for something. That promise is not iterable, so Promise.all fails. You could fix it by doing

await Promise.all(await first());

but really you should move the Promise.all into the first function itself:

async function first() {
  const oldUsers = await User.find(...);

  return Array.isArray(oldUsers)
    ? Promise.all(oldUsers.map(async (user) => {
        await User.updateOne({ _id: user._id }, { ... });
        await transporter.sendMail(sendMail(user));
      }))
    : [];
}

async function fn() {
   await first();
   await second();
   await third();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM