node.js - 使用 nodeJS 的异步 http 调用

标签 node.js http node-async

我想在我的服务器 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]

最佳答案

看看the documentation :

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/

相关文章:

ejs 文件中带有 '/' 的 CSS 链接 href 路径

http - nginx 没有那个文件或目录

javascript - 安装 browserify 后看不到 "node_modules/bin"文件夹

json - 使用 swig-template 访问 json 数据

mysql - Node-mysql WordPress在所有查询和for循环完成后获取帖子和标签并渲染页面

清除Libcurl中的cookie文件

javascript - Node.Js 错误 "No ' 请求中存在 Access-Control-Allow-Origin' header ”

node.js - 是否可以在 Node 插件中注册事件循环?

node.js - 如何在有限制的情况下运行并行进程?

javascript - 多次调用 async.eachSeries 回调