使用nodeJS进行异步http调用 [英] Asynchronous http calls with nodeJS

查看:1617
本文介绍了使用nodeJS进行异步http调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的服务器节点上启动异步http调用,我看到 async 节点模块,我想 async.parallel 使我们能够做到这一点。

I would like to launch asynchronous http calls on my server node, i saw the async node module and i guess the async.parallel enables us to do that.

文档化的示例非常清楚,但我不知道如何管理多个http调用。

The documented example is pretty clear, but i don't know how i could manage multiple http calls.

我尝试了以下示例,但它甚至没有启动http调用:

I tried the example bellow but it doesn't even launch the http calls:

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请求,我确实有结果,但是调用异步回调我获取异步回调:[null,null]

If i launch the http requests separately, i do have a result, but but calling the async callback i get async callback: [null,null]

推荐答案

看一看在文档


使用http.request()时,必须始终调用req.end()来表示您已完成请求的
- 即使没有写入数据
到请求正文。

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.

您正在创建请求,但您尚未最终确定。在您的通话中,您应该这样做:

You are creating a request, but you are not finalizing it. In your calls you should do:

var req = http.request(options, function(page) {
    // some code
});
req.end();

这假设你正在做一个没有正文的正常GET请求。

This is assuming you are doing a normal GET request without body.

您还应该考虑使用 http.get 这是一个不错的选择快捷方式:

You should also consider using http.get which is a nice shortcut:

http.get("http://127.0.0.1:3002/first", function(res) {
    // do something with result
});

更新另一件事是异步中的回调必须属于表格

Update The other thing is that callbacks in async have to be of the form

function(err, res) { ... }

现在你的方式不起作用,因为回调到http.get只接受一个参数 res 。您需要做的是:

The way you are doing it now won't work, because callback to http.get accepts only one argument res. What you need to do is the following:

http.get('http://127.0.0.1:3002/second', function(res) {
    callback(null, res);
});

这篇关于使用nodeJS进行异步http调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆