NodeJS和Sequelize的控制流程

时间:2015-02-27 16:49:22

标签: javascript node.js promise sequelize.js bluebird

我有以下功能:

 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

会多次调用{{1}}

3 个答案:

答案 0 :(得分:0)

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

基本上它会是这样的:

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

答案 1 :(得分:0)

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

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

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

Is it possible to send a variable number of arguments to a JavaScript function?

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

答案 2 :(得分:0)

您正在寻找Bluebirds collection functions,特别是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
}