2016-02-20 69 views
0

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

但是数据并没有抵制,在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}); 
      } 

编辑: 我想,也许使用像蓝鸟承诺可能与此情况有所帮助,但我不知道如何将其转换为它。

+1

不叫循环中'下一个()'的呢? – Bergi

回答

0

经过一番研究,采用蓝鸟承诺是真的优雅和简单,这解决了这个问题:

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 
}) 
相关问题