Sta*_*his 12 mongoose node.js promise node-mongodb-native bluebird
现在,父for循环(m < repliesIDsArray.length
)在第一个findOne触发之前完成,所以这只遍历repliesIDsArray..asynchronous的最后一个元素.
这个代码集的promisified版本的正确语法是什么?是新的promisification,并想知道如何启动这个promisify +循环通过数组+帐户的if语句..
蓝鸟是必需的,并被Promise.promisifyAll(require("mongoose"));
称为.
for(var m=0; m<repliesIDsArray.length; m++){
objectID = repliesIDsArray[m];
Models.Message.findOne({ "_id": req.params.message_id},
function (err, doc) {
if (doc) {
// loop over doc.replies to find the index(index1) of objectID at replies[index]._id
var index1;
for(var i=0; i<doc.replies.length; i++){
if (doc.replies[i]._id == objectID) {
index1 = i;
break;
}
}
// loop over doc.replies[index1].to and find the index(index2) of res.locals.username at replies[index1].to[index2]
var index2;
for(var j=0; j<doc.replies[index1].to.length; j++){
if (doc.replies[index1].to[j].username === res.locals.username) {
index2 = j;
break;
}
}
doc.replies[index1].to[index2].read.marked = true;
doc.replies[index1].to[index2].read.datetime = req.body.datetimeRead;
doc.replies[index1].to[index2].updated= req.body.datetimeRead;
doc.markModified('replies');
doc.save();
}
}); // .save() read.marked:true for each replyID of this Message for res.locals.username
} // for loop of repliesIDsArray
Run Code Online (Sandbox Code Playgroud)
aar*_*sil 35
正如本杰明所说,for
使用Promise.each
(或.map
)而不是使用循环
在这里查看Bluebird API文档并搜索"静态地图示例:".有map
比文档更清楚的理解each
var Promise = require('bluebird')
// promisify the entire mongoose Model
var Message = Promise.promisifyAll(Models.Message)
Promise.each(repliesIDsArray, function(replyID){
return Message.findOneAsync({'_id': req.params.message_id})
.then(function(doc){
// do stuff with 'doc' here.
})
})
Run Code Online (Sandbox Code Playgroud)
从文档中,.each
(或.map
)采用" an array, or a promise of an array, which contains promises (or a mix of promises and values)
",这意味着您可以使用100%纯值的数组来启动承诺链
希望能帮助到你!
归档时间: |
|
查看次数: |
17781 次 |
最近记录: |