在Array.map函数中使用await

时间:2017-08-09 16:41:01

标签: javascript arrays node.js asynchronous nodemailer

我需要在迭代数组之前等待异步函数完成,我需要等待解析的异步函数如下:



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




这是我在数组中迭代并尝试在它再次迭代之前等待它解决的方式的代码:



console.log('sending email to: ', person.email);




我的问题是:此行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" 一直执行,然后AMMailing.sendEmail()函数开始记录它的结果

这是我在控制台中获得的输出:

>>> help('assert')

2 个答案:

答案 0 :(得分:2)

您不需要在示例中使用map,它不会映射任何内容。您可以使用for循环遍历数组,以便按顺序等待每个项目。例如:

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

答案 1 :(得分:0)

您可以始终使用.reduce(),其初始值为Promise.resove(),并对您宣传的异步任务进行排序。

假设我们的异步sendMail(msg,cb)函数在0-250ms内发送邮件。我们可能会在sendMessages函数中宣传它(如果它没有返回承诺),并在.then()内的.reduce()阶段对承诺进行排序。

&#13;
&#13;
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);
&#13;
&#13;
&#13;