我在这里找到了很多与之相关的问题,但我无法弄清楚如何解决我的具体问题。
我有一个功能,可以获取电子邮件用户并向他们发送电子邮件。发送每封电子邮件后,我在数组中添加相应的用户ID。现在我正在实现记录器,所以我需要在日志中保存已发送的电子邮件数量,为此我只需要获取数组长度。
问题是异步,只有在向所有用户发送电子邮件后才能获得数组长度?
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
const waitFor = (ms) => new Promise(r => setTimeout(r, ms));
var sentMail = [];
module.exports = {
sendReminderMail: function(db, mail, consts){
db.find({ $and: [{ subscribed: true }] }, { $not: { feedback: true } }] }, async (err, result) => {
if (err) {
logger.error(`${err.status || 500} - ${err} - '/sendReminderMail' - 'Schedule'`);
} else {
await asyncForEach(result, async (subscriber, index) => {
await waitFor(2000 * index);
if (sentMail.indexOf(subscriber._id) < 0) {
mail.sendMail(subscriber, consts.emailType.REMINDER);
sentMail.push(subscriber._id);
}
});
}
});
}
}
我尝试过,但在这种情况下,每次迭代后调用记录器:
const waitFor = (ms) => new Promise(r => setTimeout(r, ms)).then(
logger.info(sentMail.length + 'mails was sent'));
假设我的sentMail
数组是这个[123, 987,2545]
,所以我的记录器应该保存3 mails were sent
。
您可以轻松地从该函数返回计数。
return new Promise(resolve => {
let emailCount = 0;
db.find({ $and: [{ subscribed: true }] }, { $not: { feedback: true } }] }, async (err, result) => {
if (err) {
logger.error(`${err.status || 500} - ${err} - '/sendReminderMail' - 'Schedule'`);
} else {
await asyncForEach(result, async (subscriber, index) => {
await waitFor(2000 * index);
if (sentMail.indexOf(subscriber._id) < 0) {
mail.sendMail(subscriber, consts.emailType.REMINDER);
sentMail.push(subscriber._id);
emailCount++
}
});
resolve(emailCount);
}
});
}