【问题标题】:Control-Flow with NodeJS and Sequelize使用 NodeJS 和 Sequelize 的控制流
【发布时间】:2015-04-30 11:08:47
【问题描述】:

我有以下功能:

 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会被多次调用

【问题讨论】:

  • 你应该使用Promise.map而不是forEach,这样你就可以为你的结果返回一个promise

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


【解决方案1】:

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

基本上会是这样的:

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

【讨论】:

    【解决方案2】:

    您可以使用 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() 将等到数组中的每个元素都返回并传递给您一个包含所有通知行的数组。

    【讨论】:

      【解决方案3】:

      您正在寻找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
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-21
        • 1970-01-01
        • 2021-07-20
        • 1970-01-01
        • 2018-03-12
        • 2014-08-19
        相关资源
        最近更新 更多