我想在我的服务器 Node 上启动异步 http 调用,我看到了 async
Node 模块,我想 async.parallel
使我们能够做到这一点。
记录的示例非常清楚,但我不知道如何管理多个 http 调用。
我尝试了下面的示例,但它甚至没有启动 http 调用:
var http = require('http');
var Calls = [];
Calls.push(function(callback) {
// First call
http.get('http://127.0.0.1:3002/first' callback);
});
Calls.push(function(callback) {
// Second call
http.get('http://127.0.0.1:3002/second' callback);
});
var async = require('async');
async.parallel(Calls, function(err, results) {
console.log('async callback: '+JSON.stringify(results));
res.render('view', results);
});
如果我单独启动 http 请求,我确实有一个结果,但是调用异步回调我得到 async callback: [null,null]
最佳答案
With http.request() one must always call req.end() to signify that you're done with the request - even if there is no data being written to the request body.
您正在创建一个请求,但您没有完成它。在你的电话中你应该这样做:
var req = http.request(options, function(page) {
// some code
});
req.end();
这是假设您正在执行一个没有正文的普通 GET 请求。
您还应该考虑使用 http.get这是一个不错的捷径:
http.get("http://127.0.0.1:3002/first", function(res) {
// do something with result
});
更新 另一件事是异步中的回调必须是
function(err, res) { ... }
您现在执行此操作的方式将行不通,因为对 http.get 的回调仅接受一个参数 res
。您需要做的是:
http.get('http://127.0.0.1:3002/second', function(res) {
callback(null, res);
});
关于node.js - 使用 nodeJS 的异步 http 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17106622/