【问题标题】:How to make sure that all the functions have completed their execution and send a reponse in NodeJS?如何确保所有函数都已完成执行并在 NodeJS 中发送响应?
【发布时间】:2017-10-14 17:20:50
【问题描述】:

这是我的代码:

 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 中的对象。对象是 sendEmailCount 和 receivedEmailCount。另外,我怎样才能最小化我的代码或对这两个操作使用一个函数?

【问题讨论】:

  • 是的,你应该promisifygmailObject.estimatedMessages。你试过了吗?
  • @Bergi,如果我将 gmailObject.estimatedMessages 包装到一个承诺中,那么对于每个联系人,都会为这两个功能创建一个新的承诺。我如何知道我的所有承诺都已解决并在此之后发送响应?
  • Promise.all 会这样做。
  • 使用promise让我的两个函数并行运行吗?
  • 不,同时启动两个异步的东西会使其并行。 Promise 只是让等待一个或多个结果并按顺序链接事情变得简单。

标签: node.js npm callback promise bluebird


【解决方案1】:

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

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

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

【讨论】:

  • 这些函数在 for 循环中。 Promise.all 在这种情况下可以工作吗?
  • 所以我会建议做类似的事情:contactEmailArray.map(contact =&gt; { [setSentEmailCount(contact, msg) , setReceivedEmailCount(contact, msg)] }) 并在这些函数中返回一个承诺。在这种情况下,您将创建一系列承诺并在最后解决它。
猜你喜欢
  • 1970-01-01
  • 2019-08-10
  • 1970-01-01
  • 2019-02-14
  • 2021-02-18
  • 1970-01-01
  • 2016-06-03
  • 2013-04-14
  • 1970-01-01
相关资源
最近更新 更多