【问题标题】:Why async.forEach callback is never getting called?为什么永远不会调用 async.forEach 回调?
【发布时间】:2018-11-12 02:05:07
【问题描述】:

在下面的代码中,我使用forEach 并在其中迭代一个数组,在forEach 中我调用另一个函数,同时将参数作为callback 传递,现在事情甚至我都在调用它函数的回调,forEach 回调永远不会被调用

async.forEach(Array_Ids, function (item, callback){
    sendPushNotif(item.mess, item.Ids, callback);
}, function(err) {
    // EXECUTION NEVER COMING HERE
    if(err) {
         res.json({status_code : 200, message : "Correctly Hit the URL!"});
         return next();
    } else {
         res.json({status_code : 200, message : "Correctly Hit the URL!"});
         return next();
    }
});

function sendPushNotif(mess, Ids, callback) {
sender.send(mess, { registrationTokens: Ids }, function(err, result) {
    if(err) {
        callback(null);
    }
    else {
        console.log(null);
    }
});

}

【问题讨论】:

  • 我认为sendPushNotif 不会出于某种原因调用callback。尝试以相同的方式包装回调sendPushNotif((err, res) => {console.log('Done', item); callback(err, res);});
  • @PatrickRoberts 你能再看一遍吗,谢谢。

标签: javascript node.js callback async.js


【解决方案1】:

你只能在这里有条件地调用callback()

function(err, result) {
  if(err) {
    callback(null);
  }
  else {
    console.log(null);
  }
}

如果要抑制错误,可以将if/else替换为

callback(null);

如果要传播错误,可以将整个function 表达式替换为

callback

【讨论】:

  • 实际上,我写conditions 是因为我想在那里做点什么,但由于我的代码没有成功运行,所以他们现在被留下了。
  • 不管怎样,我回答中的第一句话解释了为什么你的代码不起作用。我为您给定的示例提供了解决方案,您可以推断如何修复未共享的代码。
  • 错误是我使用的是console.log("null") 而不是callback(null) :(,我真的度过了糟糕的一天:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多