我现在有以下代码:
exports.listByUser = function(req, res) {
Attack.find({user: req.user._id}, function(err, attacks) {
if(err)
return next(err);
for(var i in attacks) {
attacks[i].evaluateFight();
}
res.json(attacks);
});
};
主要问题是异步调用attacks[i].evaluateFight()
,我想对其进行转换以确保[i-1]
迭代完成...并最终调用res.json(attacks)
。我想,可以用async完成,但我不知道如何:(这样的东西应该有用,但我怎么称呼attacks.method
?
async.eachSeries(attacks, function (callback) {
//something??
callback();
}, function (err) {
if (err) { throw err; }
res.json(attacks);
});
答案 0 :(得分:0)
您可以利用async
whilst
方法调用来实现相同的功能。但是,我对evaluateFight
的回调存在疑问,因为如果它是异步执行的,则必须有一些与之关联的回调,如果前一次调用成功,它将通知。
示例代码如下,假设evaluateFight
在完成时返回回调 -
exports.listByUser = function(req, res) {
Attack.find({user: req.user._id}, function(err, attacks) {
if(err)
return next(err);
var attacksLength = attacks.length;
var count = 0;
async.whilst(function () {
return count < attacksLength;
},
function (callback) {
attacks[count].evaluateFight(function(err, result){
count++;
callback();
}); // assuming it returns a callback on success
},
function (err) {
// all the iterations have been successfully called
// return the response
res.json(attacks);
});
};