简体   繁体   English

处理Promise.all中的错误-承诺拒绝+类型错误

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

I have few Promise.all functions: 我没有几个Promise.all函数:

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. firstsecondthird功能在一起看起来几乎相同。

first function: first功能:

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. 启动应用程序并调用fn函数时,只有第一个Promise.all成功(更新用户并发送邮件),但secondthird均未调用。

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? 我整日都在挣扎,该怎么办,所以这三个Promise.all都成功完成了吗? 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. 您的问题是Promise.all接受了一个Promise.all数组,但是您的first()函数是async ,因此返回了对某些东西的promise。 That promise is not iterable, so Promise.all fails. 这个承诺是不可迭代的,因此Promise.all失败了。 You could fix it by doing 你可以通过做来解决

await Promise.all(await first());

but really you should move the Promise.all into the first function itself: 但实际上您应该将Promise.all移到第first函数本身中:

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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