异步函数抛出错误:套接字挂起

时间:2016-03-08 03:36:06

标签: javascript node.js sockets http asynchronous

我在http请求函数中调用异步函数。被调用的异步函数执行另一个http请求,但该http请求引发错误 Error: socket hang up

代码

    var http = require("http");    
    var fs = require('fs');

    var url_1 = "en.wikipedia.org";
    var url_2 = "www.twitter.com";

    var options = { host: url_1, port: 80, path: '', method: 'POST'};    
    var api_options = { host:url_2, port: 80,path: '',method: 'POST' };


function async(arg, callback) { //async function declaration
    console.log("received argument "+ arg); 
    http.request(options, function(res){ //http request to url_2
          console.log("also the second http request successful");//this log not getting printed, insted http.request function in the previous line throws Error : socket hang up
          return callback(arg);
    });
}


http.request(options, function(res) { //http request url_1
          console.log("first http request successful");
          async("1",function(return_value){ //calling asynchronous function
            console.log("count : "+ return_value + " returns callback");
          });
}).end();

在上面的代码中,首先我正在向url_1发送http请求,请求我正在呼叫调用async函数,该函数尝试向url_2发送http请求,但{ {1}} url_2函数中的http请求只返回我上面提到的错误。

结果

async

我是node.js的新手,所以请原谅这是一个愚蠢的问题

1 个答案:

答案 0 :(得分:2)

首发:" www.twitter.com"是301 (Moved Permanently)

但是,当您使用节点时,您拥有精彩的node_modules。为什么不使用它们?

这里有got和承诺:

的样子
var request = require('got');

var url_1 = "en.wikipedia.org";
var url_2 = "google.com";

var options = { host: url_1, port: 80, path: '', method: 'POST'};    
var api_options = { host:url_2, port: 80,path: '',method: 'POST' };

request(options).then(function (res) {
    console.log('call1 ok');
    return request(api_options);
}).then(function (res) {
    console.log('call2 ok');
}).catch(function (err) {
    console.error(err);
});

要安装got,只需使用:

npm install got

选项2,如果你真的想要使用节点http模块,那么这个丑陋的东西就在这里:

var http = require("http");  

var url_1 = "en.wikipedia.org";
var url_2 = "google.com";

var options = { host: url_1, port: 80, path: '', method: 'POST'};    
var api_options = { host:url_2, port: 80,path: '',method: 'POST' };

var req1, req2;

req1 = http.request(options, function (res) {
    res.on('data', function () {
        console.log('recieved data from req1')
    })
    res.on('end', function () {
        console.log('call1 ok')
        req2 = http.request(api_options, function (res2) {
            res2.on('end', function (body) {
                console.log('call2 ok')
            });
            res2.on('data', function () {
                console.log('recieved data from req2')
            });
        });
        req2.end();
    });
});
req1.end();

如果您不.end() http.request(),则会引发套接字挂断错误。见Node documentation