[英]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. first
, second
和third
功能在一起看起来几乎相同。
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));
}) : [];
};
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
成功(更新用户并发送邮件),但second
和third
均未调用。
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.