小编典典

Bluebird Promisfy.each,带有for循环和if语句?

node.js

现在,父级for循环(m < repliesIDsArray.length)在第一个findOne触发之前完成,因此,这仅循环通过repliesIDsArray..asynchronous。的最后一个元素。

此代码集的承诺版本的正确语法是什么?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

阅读 222

收藏
2020-07-07

共1个答案

小编典典

正如本杰明所说,不要使用for循环,而应使用Promise.each(或.map

此处查看Bluebird
API文档然后搜索“静态地图示例:”。与map相比,对于Doc的理解更清晰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.  
        })
})

从文档中,.each(或.map)采用“ an array, or a promise of an array, which contains promises (or a mix of promises and values)”,这意味着您可以将其与100%纯值数组一起使用以启动承诺链

希望能帮助到你!

2020-07-07