执行所有超时后如何获取数组大小

时间:2019-04-23 15:00:37

标签: javascript node.js async-await

我在这里发现了很多与之相关的问题,但是我不知道该如何解决我的特定问题。

我有一个获取电子邮件用户并向他们发送电子邮件的功能。 发送每封电子邮件后,我将各自的用户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

1 个答案:

答案 0 :(得分:0)

You could easily return the count from that function.

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