[英]use await inside Array.map function
在遍歷數組之前,我需要等待異步函數完成,需要等待解決的異步函數如下:
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); } }); }); }
這是我在數組中進行迭代並嘗試等待其解決之后再進行迭代的方式的代碼:
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);
一直執行,然后AMMailing.sendEmail()函數開始記錄其結果
這是我在控制台中得到的輸出:
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"
您無需在示例中使用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);
}
}
}
您可以隨時使用.reduce()
用的初始值Promise.resove()
和順序您promisified異步任務。
假設我們的異步sendMail(msg,cb)
函數在0-250ms內發送郵件。 我們可以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.