Asynchronous http calls with nodeJS

旧城冷巷雨未停 提交于 2019-11-30 22:13:59

Have a look at 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.

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();

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

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) { ... }

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);
});

dont use capital names for other purpouses than types/classes

below is your code with corrected obvious mistakes

var http = require('http');

var calls = [];
calls.push(function(callback) {
    // First call
    http.get('http://127.0.0.1:3002/first', function (resource) {
         resource.setEncoding('utf8');
         resource.on('data', function (data) {
             console.log('first received', data);
             callback();
         });
    });
});

calls.push(function(callback) {
    // Second call
    http.get('http://127.0.0.1:3002/second', function (resource) {
         resource.setEncoding('utf8');
         resource.on('data', function (data) {
             console.log('second received', data);
             callback();
         });
    });
});

var async = require('async');
async.parallel(calls, function(err, results) {
    console.log('async callback ', results);
    res.render('view', results);
});

Ok the thing is to call the callback this way callback(null, res); instead callback(res);, i think the first parameter is interpreted as an error and the second one is the real result.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!