2011-11-19 45 views
2

對不起,如果這個問題很簡單,但我一直在使用node.js幾天。Node.js:檢測請求的所有事件何時完成

基本上我收到一個json的一些條目。我循環這些條目併爲其中的每個啓動一個http請求。類似這樣的:

for (var i in entries) { 
    // Lots of stuff 

    http.get(options, function(res) { 
     // Parse reponse and detect if it was successfully 
    }); 
} 

如何檢測何時完成所有請求?我需要這個以調用response.end()。

另外,我將需要通知,如果每個條目都成功或沒有。我應該使用全局變量來保存每個條目的結果嗎?

+0

重複http://stackoverflow.com/questions/5172244/idiomatic-way-to-wait-for-multiple-callbacks-in-node-js/5175674和http://stackoverflow.com/questions/7721808 /如何獲取兩個異步函數的參數/ 7722015 –

回答

4

您可以使用caolans "async"庫:

async.map(entries, function(entry, cb) { 
    http.get(options, function(res) { 
    // call cb here, first argument is the error or null, second one is the result 
    }) 
}, function(err, res) { 
    // this gets called when all requests are complete 
    // res is an array with the results 
} 
+0

如果你只是簡單地循環一些項目,我建議使用'async.each'而不是'async.map'。由於[map](https://github.com/caolan/async#maparr-iterator-callback)會通過映射每個值**來生成一個新的數組值,這會導致更多的開銷。 –

0

有許多不同的庫。我更喜歡qqq期貨庫到async,因爲async導致複雜場景下的回調森林。另一個庫是Step

相關問題