【问题标题】:expressJs multiple callbacks manipulating the same data objectexpressJs 多个回调操作相同的数据对象
【发布时间】:2016-06-01 19:01:52
【问题描述】:

我有一个场景,我需要在下面的系列中进行多次调用。 我正在更新“loadBaseData”函数返回的主数据对象,然后需要再次调用“grindCoffee”函数对同一数据对象进行额外修改。

但是数据没有抵抗,到了processResponse的时候,所有的选项都是空的。

app.post('/makecoffee', loadBaseData, grindCoffee, addWater, brewCoffee, processResponse);

        function loadBaseData (req, res, next) {
          pgServer.dbSelectData(req.body.username)
            .then(function(data) { 
              req.data = data;
              next();
            })
            .catch(function(err) { 
              res.send({success:false,message:'error, '+ err}); 
            });  
        }

            function grindCoffee (req,res,next){
              var records = req.data;

              for (j = 0; j< records.length; j++) { 
                if (Condition A){
                  dsServer.grindCoffee(function(res){          
                      if (Condition B){
                        req.data[i].options = res;
                        next();
                      }                    
                  });            
                }
              }
              next();
            }  
        // addWater and brewCoffee are similar to grindCoffee, it keeps updating the req.data

            function processResponse(req,res){
              res.send({success:true,data:req.data});
            }

编辑: 我认为也许使用像 bluebird 这样的 promise 可能有助于解决这种情况,但我不确定如何将其转换为它。

【问题讨论】:

  • 不要在循环中调用next()

标签: node.js express promise bluebird


【解决方案1】:

经过一番研究,使用bluebird Promise确实优雅简单,这样就解决了问题:

var Promise = require("bluebird");

//all sub tasks such as grindCoffee, addWater, and brewCoffee need to be turn into promises like this

function grindCoffeeAsync (){
  return new Promise(function(resolve,reject){
    dsServer.grindCoffee(function(data){
      resolve(data);
    });
  });
}

  Promise.all([
      pgServer. dbSelectData(username),
      grindCoffeeAsync(),
      addWaterAsync(),
      brewCoffeeAsync()
    ])
    .spread(function(p1,p2, p3, p4){
      //p1 is the result from the first promise
      //p2 is the result from the second promise.....
      //you can manipulate all 4 results here
      var allObjects = [];
      allObjects.push(p1);
      allObjects.push(p1);
      allObjects.push(p1);
      allObjects.push(p1);

      return allObjects;
}).then(function(result){
   console.log(result); //you will get all 4 results from allObjects
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    相关资源
    最近更新 更多