【发布时间】:2014-09-26 10:05:13
【问题描述】:
现在,父 for 循环 (m < repliesIDsArray.length) 在第一个 findOne 触发之前完成,所以这一切只循环通过 repliesIDsArray..asynchronous..的最后一个元素..
此代码集的承诺版本的正确语法是什么?我是 Promisification 的新手,想知道如何开始这个 Promisify + 遍历数组 + 考虑 if 语句..
需要Bluebird,并调用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
【问题讨论】:
-
您可以使用
Promise.each和.fineOneAsync -
@BenjaminGruenbaum 感谢您的提醒.. 测试这个:
Promise.each(function(repliesIDsArray) { console.log('is repliesIDsArray here now equivalent to repliesIDsArray[i] ? ' + repliesIDsArray ); });虽然记录了这个:Possibly unhandled TypeError: fn must be a function.. 肯定会很感激一个如何开始这个的例子
标签: node.js mongoose promise node-mongodb-native bluebird