蓝鸟Promisfy.each,for循环和if语句?

现在,父对象循环( m < repliesIDsArray.length )在第一个findOne触发之前完成,所以这全部只循环通过respondIDsArray.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 

正如Benjamin所说的,不是使用for循环,而是使用Promise.each (或.map

在这里查看Bluebird API文档并search“静态地图示例:”。 与mapeach文件更清楚地了解

 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 )需要“ an array, or a promise of an array, which contains promises (or a mix of promises and values)an array, or a promise of an array, which contains promises (or a mix of promises and values) ”,这意味着您可以使用100%纯数组开创诺言链的价值

希望能帮助到你!