[英]using async with javascript forEach
I have an array of emails我有一系列电子邮件
emails.forEach(email => sendEmail(email)); --> 1
function2();
sendEmail is an asynchronous function I want function2 to be invoked only after line 1 gets completed sendEmail 是异步 function 我希望仅在第 1 行完成后调用 function2
How can I achieve this?我怎样才能做到这一点?
How can I achieve this?
我怎样才能做到这一点?
Don't use forEach
.不要使用
forEach
。 Either use a normal for loop, and await
each call, or if you want to run them in parallel use map
and await Promise.all
.要么使用普通的 for 循环,然后
await
每个调用,或者如果您想并行运行它们,请使用map
并await Promise.all
。
My preference would be:我的偏好是:
async function sendAllEmails(emails) {
await Promise.all(emails.map(email => sendEmail(email)));
function2();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.