【问题标题】:Node.js: detect when all events of a request have finishedNode.js:检测请求的所有事件何时完成
【发布时间】:2011-11-19 22:07:38
【问题描述】:

对不起,如果这个问题很简单,但我使用 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()。

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

【问题讨论】:

标签: node.js


【解决方案1】:

你可以例如使用 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
}

【讨论】:

  • 如果你只是简单地循环一些项目,我建议使用async.each 而不是async.map。由于map通过映射每个值来生成一个新的值数组,因此会导致更多开销。
【解决方案2】:

为此有许多不同的库。我更喜欢qqq 期货库而不是async,因为async 会导致复杂场景中的回调森林。还有一个库是Step

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    • 1970-01-01
    • 2015-04-17
    • 2017-09-03
    • 2018-12-10
    相关资源
    最近更新 更多