简体   繁体   English

在Array.map函数中使用await

[英]use await inside Array.map function

I need to wait for a async function to complete before iterating over the array, the asynchronous function i need to wait to resolve is as follows: 在遍历数组之前,我需要等待异步函数完成,需要等待解决的异步函数如下:

 static async sendEmail (from, to, subject, text) { return new Promise((resolve, reject) => { let message = { from, to, subject, text }; AMMailing.transporter.sendMail(message, function (err, response) { if (err) { reject(err); } else { resolve(response); } }); }); } 

This is the code of the way i'm iterating in the array and trying to wait for it to resolve before it iterates again: 这是我在数组中进行迭代并尝试等待其解决之后再进行迭代的方式的代码:

 static sendEmailInQueue (queue) { queue.map(async (person, index) => { console.log('sending email to: ', person.email); try { let success = await AMMailing.sendEmail(AMMailing.message.from, person.email, AMMailing.message.subject, AMMailing.message.text); if (success) { console.log('email sent to: ', person.email); } } catch (err) { console.log(err); } }); } 

My problem is: this line console.log('sending email to: ', person.email); 我的问题是:这行console.log('sending email to: ', person.email); is executed all times and then the AMMailing.sendEmail() function start to log it's results 一直执行,然后AMMailing.sendEmail()函数开始记录其结果

this is the output i get in the console: 这是我在控制台中得到的输出:

sending email to:  matheus.rezende10@gmail.com
sending email to:  matheus.rezende10@gmail.com
sending email to:  matheus.rezende10@gmail.com
sending email to:  matheus.rezende10@gmail.com
sending email to:  matheus.rezende10@gmail.com
sending email to:  matheus.rezende10@gmail.com
sending email to:  matheus.rezende10@gmail.com
sending email to:  matheus.rezende10@gmail.com
sending email to:  matheus.rezende10@gmail.com
sending email to:  matheus.rezende10@gmail.com
sending email to:  matheus.rezende10@gmail.com
{ Error: Hostname/IP doesn't match certificate's altnames: "Host: mail.appmasters.io. is not in the cert's altnames: DNS:*.sgcpanel.com, DNS:sgcpanel.com"

You don't need to use map in your example, it is not mapping anything. 您无需在示例中使用map ,它没有映射任何内容。 You can simply iterate over your array with for-loop to await on each item sequentially. 您可以简单地使用for循环遍历数组,以按顺序等待每个项目。 For example: 例如:

static async sendEmailInQueue (queue) { // async method
  for (let i = 0; i < queue.length; i++) {
    try {
      // await sequentially
      let success = await AMMailing.sendEmail(/* ... */);
      if (success) {
        console.log('email sent to: ', person.email);
      }
    } catch (err) {
      console.log(err);
    }
  }
}

You may always use a .reduce() with an initial value of Promise.resove() and sequence your promisified asynchronous tasks. 您可以随时使用.reduce()用的初始值Promise.resove()和顺序您promisified异步任务。

Assume that our asynchronous sendMail(msg,cb) function sends a mail in 0-250ms. 假设我们的异步sendMail(msg,cb)函数在0-250ms内发送邮件。 We may promisify it (in case it doesn't return a promise) in our sendMessages function and sequence the promises up with .then() stages within a .reduce() . 我们可以promisify它在我们的(如果它不返回一个承诺) sendMessages功能和顺序的承诺了.then()阶段中.reduce()

 function sendMail(msg, cb){ setTimeout(cb, Math.random()*250, false, "message to: " + msg.to + " is sent"); } function sendMessages(ms){ function promisify(fun, ...args){ return new Promise((v,x) => fun(...args, (err,data) => !!err ? x(err) : v(data))); } ms.reduce((p,m) => p.then(v => promisify(sendMail,m)) .then(v => console.log(v)), Promise.resolve()); } var msgArray = [{from: "x", to: "John@yyz.com", subject: "", text:""}, {from: "y", to: "Rose@ist.com", subject: "", text:""}, {from: "z", to: "Mary@saw.com", subject: "", text:""} ]; sendMessages(msgArray); 

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

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