如何确保所有功能都已完成执行并在 NodeJS 中发送响应?

How to make sure that all the functions have completed their execution and send a reponse in NodeJS?

这是我的代码:

 route.get('/',function(req, res){
 for(var e = 0; e < contactEmailArray.length; e++){
        var currentContact = contactEmailArray[e];
        setSentEmailCount(gmail, currentContact);
        setReceivedEmailCount(gmail, currentContact)
    }
  //send contactEmailArray as response after everything is completed
   });

  function setSentEmailCount(gmailObject, currentContact){
    var s = gmailObject.estimatedMessages ('from:(mohitmaharjan@gmail.com) to:('+currentContact.email+')', { fields: []}, function(err, estimatedMessages){
    currentContact.sentEmailCount = estimatedMessages;
    console.log(currentContact.email + ' : ' + currentContact.sentEmailCount);
    sentResponseCount++;
    if(sentResponseCount == countOfContactHavingEmail){
        console.log('sent operation completed');
    }
    console.log('Counter Value : ' + sentResponseCount);
    });
 }

 function setReceivedEmailCount(gmailObject, currentContact){
    var s = gmailObject.estimatedMessages ('from: ('+currentContact.email+') to:(mohitmaharjan@gmail.com)', { fields: []}, function(err, estimatedMessages){
    currentContact.receivedEmailCount = estimatedMessages;
    console.log(currentContact.email + ' : ' + currentContact.receivedEmailCount + ' received');
    receivedResponseCount++;
    if(sentResponseCount == countOfContactHavingEmail){
        console.log(' received operation completed');
    }
    console.log('Counter Value : ' + receivedResponseCount);
   });
 }

我需要在完成每个联系人的 setSentEmailCountsetReceivedEmailCount 这两个函数后发送回复。这两个函数都会更新 contactEmailArray 中的对象。对象是 sentEmailCount 和 receivedEmailCount。另外,我怎样才能最小化我的代码或对这两个操作使用一个函数?

也许你可以尝试将这些函数包装到 promise 中并通过 es7 解析它 async/await?

//async
await Promise.all([setSentEmailCount, setReceivedEmailCount])

下一个想法是使用 middlewaressetSentEmailCount(gmail, currentContact, next) 然后使用它 - 通过 next()setReceivedEmailCount 函数中?