asynchronous(同步)函数/空结果的callback不能进入

所以我使用asynchronous,这个函数会输出一些ID和计数的结果,但不是“callback”

getWaitingGames: function(req,res){ var me = req.session.passport.user; var rez=[]; console.log("meeeeeeeeee"); console.log(me); GivenQuestion.find().where({user_id:me}).exec(function(err,data){ var tpm_id = data[0].partie_id; console.log(tpm_id); console.log(data); async.each(data, function(d, callback) { var parties = []; if (d.partie_id != tpm_id){ console.log(d.partie_id); parties.push(d.partie_id); tpm_id=d.partie_id; GivenQuestion.count().where({ partie_id: d.partie_id, user_id: me }).exec(function(e, countRes) { console.log(countRes); if (countRes==2){ rez.push(d.partie_id); callback(); } }); } }, function(err) { if (err) { console.log(error); } else{ console.log("callback"); res.ok(rez); } }); }); }, 

这是为什么? 我找不到我要做的错误,似乎和文档一样,我以前也用过

编辑:是的,我可以把callback之后,如果你们喜欢你们build议,但是我得到一个空的雷斯。 为什么? asynchronous只能工作一个级别? (我的意思是,我在里面2 .exec())

代码中有一个小问题。 在async.each方法的情况下,在作为处理函数的第二个参数中,我们必须调用callback()移动到下一个元素。 如果我们不调用callback(),那么如果永远不会出现function。

在你的情况下,只有在if (countRes==2)的情况下才会调用callback( if (countRes==2) ,但其他情况如何? 在其他情况下, async.each()等待callback()处理数据中的下一个项目,但由于我们没有调用callback(),所以等待它。

解决scheme:在if (countRes==2)之外调用callback( if (countRes==2) 。 请查看下面的代码片段了解更多详情:

 GivenQuestion.count().where({ partie_id: d.partie_id, user_id: me }).exec(function(e, countRes) { console.log(countRes); if (countRes==2){ rez.push(d.partie_id); } callback(); }); 

如果您仍然发现问题,请回复。

需要两个input来更深入地了解这个问题:

  1. 你检查条件if(countRes == 2)结果为吗? 因为如果这个条件评估为falserez永远是空的

  2. 如果if(countRes == 2)的计算结果为true ,那么在这种情况下, d.partie_id的值是多less

请提供这些input。

另外, async.each也可以在多个层面上工作。 我做了一个实现,我在asynchronous内使用asynchronous。 所以,它看起来不像asynchronous的错误。