2013-06-26 39 views
0

我不能合併結果的每個發現這個代碼功能:遞歸查找函數調用然後合併結果

this.result = []; 
    _products.find().exec(function (err,products) { 
     this.products = products; 
     var productsCollection = []; 
     for(i=0;i<products.length;i++) { 
      _prices.find({uname:products[i].uname},function(err,prices){ 

       var resultItem = {product:products[i],prices:prices} 
       this.result.push(resultItem) 
      }.bind(this)) 

     } 
      res.json(200, this.result); 
    }.bind(this)); 

沒有錯誤...但響應是一個空數組:(

請幫助...我如何合併結果?

回答

1

由於.find是異步的,因此您在調用res.json之前先調用res.json。簡單的解決方案是使用async來遍歷數組並在全部結果爲a時調用res.json重新收到。

var async = require('async'); 
this.result = []; 

_products.find().exec(function (err, products) { 
    // async.map takes an array and constructs a new array from it 
    // async.each and this.result.push() would also work but I find .map to be cleaner 
    async.map(products, function (product, next) { 
     _prices.find({ uname: product.uname }, function(err, prices){ 
      // By passing the object to next here it will be passed to the 
      // final callback below 
      next(err, { product: product, prices: prices }); 
     }); 
    }, function (err, result) { 
     // This callback will nicely wait until all queries above has finished 
     this.result = result; 
     res.json(200, result); 
    }); 
}.bind(this)); 
+0

謝謝你verry musch ...我是一個php開發人員...不知道異步:D –