Node.js:检测请求的所有事件何时完成

Fer*_*ndo 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
    });
}
Run Code Online (Sandbox Code Playgroud)

如何检测所有请求何时完成?我需要这个以便调用response.end()。

我也需要告知每个条目是否成功。我应该使用全局变量来保存每个条目的结果吗?

the*_*ejh 5

您可以例如使用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
}
Run Code Online (Sandbox Code Playgroud)