Node.js:检测请求的所有事件何时完成
如果这个问题很简单,很抱歉,但我只使用了node.js几天 基本上,我收到一个带有一些条目的json。我对这些条目进行循环,并为每个条目启动http请求。大概是这样的:Node.js:检测请求的所有事件何时完成,node.js,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 }); } 如何检测所有请求何时
for (var i in entries) {
// Lots of stuff
http.get(options, function(res) {
// Parse reponse and detect if it was successfully
});
}
如何检测所有请求何时完成?我需要这个来调用response.end()
此外,我还需要通知,如果每个条目成功或没有。我应该使用全局变量保存每个条目的结果吗?您可以使用caolans库:
有许多不同的库可以实现这一点。我更喜欢
q
和qq
未来库而不是async
,因为async
在复杂场景中会导致大量回调。还有一个库是Step
的副本,如果您只是简单地循环某些项,我建议使用async.each
而不是async.map
。由于will通过映射每个值来生成一个新的值数组,因此会导致更多的开销。
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
}