在我的下面的代码中,onResolve()函数在第一个函数之前调用,然后在其他函数之前调用(在req.body.length> 1时看到它)。知道为什么吗?我想将保存的资产列表添加到数组中,然后在所有findOneAndUpdate执行完成后在响应中发送该数组。
exports.saveAssetLists = function(req, res) {
console.log('starting save asset lists');
if (!Common.testIfValidForSave(req.body, true)) {
res.status(400).send({error:'Invalid request body: ' + JSON.stringify(req)});
return;
}
var deferred = null;
var savedAssetLists = [];
for (var i = 0; i < req.body.length; i++) {
var newAssetList = new AssetList(req.body);
var d = AssetList.findOneAndUpdate({_id: newAssetList._id }, newAssetList, {upsert:true, new:true}).exec().then(function(obj) {
console.log('then - obj: ' + JSON.stringify(obj));
savedAssetLists.push(obj);
});
if (!deferred) {
deferred = d;
} else {
deferred.chain(d);
}
}
deferred.onResolve(function(err, result) {
console.log('onResolve - err: ' + err + ', result: ' + result + ', savedAssetLists: ' + savedAssetLists);
res.send({data: savedAssetLists});
})
.onReject(function(err) {
res.status(500).send({error: err});
});
return deferred;
};
这是日志输出:
starting save asset lists
then - obj: {"_id":"561eafe95c0df2c0468cb798","name":"Asset List 1","__v":0,"assets":[null]}
onResolve - err: null, result: undefined, savedAssetLists: { _id: 561eafe95c0df2c0468cb798,
name: 'Asset List 1',
__v: 0,
assets: [ null ] }
then - obj: {"_id":"561eafe95c0df2c0468cb799","name":"Asset List 2","__v":0,"assets":[null]}
根据Vsevolod的建议,我将代码更改为以下内容,但是后来的方法永远不会被调用:
exports.saveAssetLists = function(req, res) {
console.log('starting save asset lists');
if (!Common.testIfValidForSave(req.body, true)) {
res.status(400).send({error:'Invalid request body: ' + JSON.stringify(req)});
return;
}
var promises = [];
var savedAssetLists = [];
for (var i = 0; i < req.body.length; i++) {
var newAssetList = new AssetList(req.body[i]);
var p = AssetList.findOneAndUpdate({_id: newAssetList._id }, newAssetList, {upsert:true, new:true}).exec();
promises.push(p);
}
Promise.all(promises).then(function(values) {
console.log('onResolve - err: ' + err + ', values: ' + values + ', savedAssetLists: ' + savedAssetLists);
res.send({data: values });
}, function(err) {
res.status(500).send({error: err});
});
};
答案 0 :(得分:0)
您可以做的是从req.body
创建一系列承诺:
var promises = req.body.map(function(data){
var newAssetList = new AssetList(data);
return AssetList.findOneAndUpdate({_id: newAssetList._id }, newAssetList, {upsert:true, new:true})
});
Promise.all(promises).then(function(results){
return res.send({data: results});
}).catch(function(err){
return res.status(500).send({error: err});
});
小注意:代码中不需要mpromise
库。这应该适用于猫鼬4 +