Nodejs http请求不从递归函数调用

时间:2014-02-04 11:29:44

标签: javascript node.js

我有一个奇怪的情况

我需要发送请求3次或直到我得到正确的回复

var connect = function(){ 

  console.log('first step');

  var connector = http.request(some_options, function(resp) {

    console.log('sec step');

    resp.on("data", function(chunk){
        str += chunk;
    });
    resp.on("end", function() {

      console.log('third step');

      if (resp.statusCode != 200){
        return false
      }
      else{
        var rep = 3;
        var i = 1;
        (function retry_connect(){                                          
           if ((i <= rep) && JSON.parse(str).hasOwnProperty('error')) {
             console.log('reconnect');
             connect();
             i++;
             setTimeout(function(){retry_connect()}, 3000);                             
           }
           else{
             return true
           }
        }());
      }
    });
  });
};

connect();

此处输出此代码:

first step
sec step
third step
reconnect
first step
first step
first step

可以解释为什么连接器没有从retry_connect()函数调用?

由于

1 个答案:

答案 0 :(得分:0)

您的http.request可能会发出错误, 尝试添加:

connector.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

顺便说一句。你的回复陈述不会做任何事情也可能省略它们

http.request也是一个异步函数,(因此连接的返回是异步的) 你迭代我... rep并递归调用connect()并设置一个超时来调用retry_connect 总共3次​​,反过来会做同样的,但现在是3次等等。

生病,因为你对整个回复机构感兴趣

function connect (opts, callback, count) {

    if (count > 3) {
        console.log('retry limit reached');
        callback({error:'retry limit reached'});
    } else {
        var request = http.request(opts, function (response) {
            var buffer = [];

            response.on('data', function (chunk) {
                buffer.push(chunk);
            });
            response.on('end', function () {
                var data = buffer.join('');
                if (response.statusCode !== 200) {
                    console.log('did not receive a 200 OK');
                    callback({error: {statusCode: response.statusCode}});
                } else {
                    //200 OK but the json data might contain an error
                    var parsed = JSON.parse(data);
                    if (parsed.error) {
                        count = (count||0) +1;
                        console.log('retrying in ' + (count * 3000));
                        setTimeout(function () {
                            console.log('retrying now');
                            connect(opts, callback, count);
                        }, 3000 * count);
                    } else {
                        console.log('200 OK and no error in json, calling callback with parsed json response');
                        callback(null, parsed);
                    }
                }
            });

        });

        request.on('error', function (error) {
            console.log('request error', error);
            callback({error:error});
        });
    }

}

connect({host: 'example.com'}, function (err, data) {
    if (err) {
        console.log('something went wrong:', err);
    } else {
        console.log('request done:', data);
    }
});

由于所有这些都是异步的,你需要一些机制才能在事情完成/失败时发回信号,我已经使用回调来做到这一点。