繁体   English   中英

NodeJS和Sequelize的控制流程

[英]Control-Flow with NodeJS and Sequelize

我有以下功能:

 function retrieveNotifications(promotions) {
         promotions.forEach( function(promotion) {

             //find all notification groups that have to be notified
             db
               .Notification
                   .findAll()
                       .then(function (notifications) {
                           //some code that adds notifications to an object
                        });                       
         });         
  };

如何重新构建它以等待所有通知都添加到对象。 我不能使用.then因为forEach会被多次调用

我建议使用异步库: https//github.com/caolan/async

基本上它会是这样的:

async.parallel([ 
  // tasks..
], 
function () {
  // this is the final callback
})

您可以使用内置于Sequelize / Bluebird中的.spread():

https://github.com/petkaantonov/bluebird/blob/master/API.md#spreadfunction-fulfilledhandler--function-rejectedhandler----promise

让你的forEach构建一个db.Notification.findAll()数组并返回它。 然后在结果上调用.spread。 如果您不知道返回的数组的长度,则可以在成功回调中使用arguments对象。

是否可以向JavaScript函数发送可变数量的参数?

现在.spread()将一直等到数组中的每个元素都返回并传递一个包含所有Notification行的数组。

您正在寻找Bluebirds集合函数 ,特别是mapeachprop 它们将允许您使用异步回调迭代promotions数组,并且您将获得一个仅在所有这些回复完成后自动解析的回复。

在你的情况下,它看起来像这样:

function retrieveNotifications(promotions) {
    return Promise.map(promotions, function(promotion) {
        // find all notification groups that have to be notified
        return db.Notification.findAll(… promotion …);
    }).then(function(results) {
        // results is an array of all the results, for each notification group
        var obj = {};
        for (var i=0; i<results.length; i++)
            //some code that adds notifications to the object
        return obj;
    });
    // returns a promise for that object to which the notifications were added
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM