Search code examples
node.jsnpmcallbackpromisebluebird

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


Here is my code:

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

I need to send a response after these two function setSentEmailCount and setReceivedEmailCount are completed for every contact. Both functions will update the objects inside the contactEmailArray. Objects are sentEmailCount and receivedEmailCount. Also, how can I minimize my code or use a single function for both the operations?


Solution

  • Maybe you can try to wrap those functions into promise and resolve it by es7 async/await ?

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

    Next idea for that, is to use middlewares, setSentEmailCount(gmail, currentContact, next) and after that use it - by next() in setReceivedEmailCount function ?