如果我需要按顺序调用3个http API,那么比起下面的代码,哪种方法更好:
http.get({ host: 'www.example.com', path: '/api_1.php' }, function(res) {
res.on('data', function(d) {
http.get({ host: 'www.example.com', path: '/api_2.php' }, function(res) {
res.on('data', function(d) {
http.get({ host: 'www.example.com', path: '/api_3.php' }, function(res) {
res.on('data', function(d) {
});
});
}
});
});
}
});
});
}
发布于 2011-05-19 01:29:40
使用像Futures
这样的延迟。
var sequence = Futures.sequence();
sequence
.then(function(next) {
http.get({}, next);
})
.then(function(next, res) {
res.on("data", next);
})
.then(function(next, d) {
http.get({}, next);
})
.then(function(next, res) {
...
})
如果您需要传递作用域,那么只需执行以下操作
.then(function(next, d) {
http.get({}, function(res) {
next(res, d);
});
})
.then(function(next, res, d) { })
...
})
发布于 2011-05-21 07:34:50
我也喜欢Raynos的解决方案,但我更喜欢不同的流控制库。
https://github.com/caolan/async
根据您是否需要每个后续函数中的结果,我将使用串行、并行或瀑布。
当它们必须串行执行时使用Series,但您不一定需要在后续的每个函数调用中都使用结果。
Parallel如果它们可以并行执行,那么在每个并行函数中都不需要每个函数的结果,并且当所有函数都完成时,您需要一个回调。
如果要将每个函数中的结果变形并传递给下一个函数,则为Waterfall
endpoints =
[{ host: 'www.example.com', path: '/api_1.php' },
{ host: 'www.example.com', path: '/api_2.php' },
{ host: 'www.example.com', path: '/api_3.php' }];
async.mapSeries(endpoints, http.get, function(results){
// Array of results
});
发布于 2015-03-20 01:57:39
到目前为止,我找到并使用的最简单的是sync-request,它同时支持节点和浏览器!
var request = require('sync-request');
var res = request('GET', 'http://google.com');
console.log(res.body.toString('utf-8'));
就是这样,没有疯狂的配置,没有安装复杂的库,尽管它确实有一个库后备。很管用。我试过这里的其他例子,当有很多额外的设置要做或安装不起作用时,我被难住了!
备注:
当您使用res.getBody()
时,sync-request使用的示例并不好用,所有get body所做的就是接受编码并转换响应数据。只需执行res.body.toString(encoding)
即可。
https://stackoverflow.com/questions/6048504
复制相似问题