2017-05-09 67 views
0

我有三個操作做彼此的NodeJS-異步:返回MySQL查詢結果爲循環

1.Fetch之後,從DB

2.Another MySQL查詢一些行的for循環用於獲取的一些數據和存儲在變量

3.顯示數據

對於我使用asyncwaterfall方法。

async.waterfall([ 
      function(callback){ 
       //first sql and pass the result to second function 
       collection.getAllCollections(function (status,error,result) { 
        callback(null,result); 
       }); 
      }, 
      //running another query in loop with result with previous 
      function(result, callback){ 
       for(var i=0;i<result.length;i++){ 
        collection.getImages(result[i].id,function (status,error,user) { 
         //append the query result to old result 
         result[i]['users'] = user; 
        }); 
       } 
       callback(null,result); 
      } 
     ], function (err, result) { 

      console.log("result",result); 
     }); 

但問題最終result不會因爲第二個查詢(在for循環是異步查詢)

回答

1

你意識到手頭的問題包含user結果。你的回調基本上必須等待for循環結束。 例如像這樣:

async.waterfall([ 
    function(next){ 
     //first sql and pass the result to second function 
     collection.getAllCollections(function (status,error,result) { 
      next(null, result); 
     }); 
    }, 
    function(result, next){ 
     var calls = []; 

     //putting every call in an array 
     result.forEach(function(resultObject){ 
      calls.push(function(callback) { 
       collection.getImages(resultObject.id, function (status, error, user) { 
        resultObject['users'] = user; 
        callback(null, resultObject); 
       }); 
      } 
     )}); 

     //performing calls async parallel to each other 
     async.parallel(calls, function(err, results) { 
      //executed as soon as all calls are finished 
      if (err) { 
       next(err, null); 
      } else { 
       next(null, results); 
      } 
     }); 
    } 
], function (err, result) { 

    console.log("result",result); 
}); 

文檔:http://caolan.github.io/async/docs.html#parallel

+0

但是,在可以把'isDone'功能?我正在使用異步瀑布方法 – Jabaa

+0

@Jabaa我更新了我的代碼以闡明我的解決方案。這應該工作,但我沒有測試它。 – jpschack

+0

@Jabaa我再次更新了我的答案。使用async.parallel可以提供更好,更清潔,更高效的解決方案。這應該讓你朝正確的方向發展。 – jpschack