Node.js Bluebird Promisfy.each,带有for循环和if语句?
现在,循环的父循环(Node.js Bluebird Promisfy.each,带有for循环和if语句?,node.js,mongoose,promise,node-mongodb-native,bluebird,Node.js,Mongoose,Promise,Node Mongodb Native,Bluebird,现在,循环的父循环(m
m
)在第一个findOne激发之前完成,因此这一切只循环repliesdsarray.asynchronous的最后一个元素
此代码集的预期版本的正确语法是什么?我是promisification的新手,不知道如何启动Promisifiy+循环,遍历arrays+account for if语句
蓝鸟是必需的,promisifyAll(必需(“猫鼬”)代码>被调用
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
for(var m=0;m正如Benjamin所说,不要使用for
循环,而是使用承诺。每个(或.map
)
查看Bluebird API文档并搜索“静态映射的示例:”。对于每个
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.
})
})
从文档中,.each
(或.map
)获取“一个数组,或数组的承诺,其中包含承诺(或承诺和值的组合)
”,这意味着您可以将其与100%纯值数组一起使用,以启动承诺链
希望有帮助!您可以使用Promise.each
和.fineOneAsync
@BenjaminGruenbaum感谢您的提醒..测试:Promise.each(函数(repliesdarray){console.log('repliesdarray现在等于repliesdarray[i]?'+repliesdarray);});
记录此操作:可能未处理的类型错误:fn必须是一个函数
。请举个例子说明如何启动此操作。此操作不起作用,您必须在中的函数中返回承诺。每个
,否则它无法知道承诺已完成。如果您对文档有任何建议,我将我很高兴听到它们并进行相应的编辑。谢谢我纠正了好的问题。文档是很棒的。我唯一想添加的是的“静态”示例。每个都可能。我把他指给“静态地图”部分,因为它有一个从array@BenjaminGruenbaum谢谢你的帮助,现在很好用很高兴我能帮上忙。享受蓝莓吧d、 如果您有任何反馈、建议等,我们很乐意听到。感谢您的快速回复@aarosil。实际上它工作正常。我在代码中有其他问题。现在工作正常。