Nodejs http 请求延时的处理方法(防止程序崩溃)

有时候因为接口没开,或者其他原因,导致http.request 请求延时,一直耗费资源不说,还会导致程序报错崩溃,延时处理其实也是一种错误处理。

var APIGET = function (url, callback) {
    debug("向API服务请求数据中...");
    debug("url:"+url)
//下面是发送请求时的延时处理,一般用不到
    var requestTimer = setTimeout(function () {
        req.abort();
        debug('......Request Timeout......');
    },5000);
    var op = {
        host:CONFIG.API_SERVICE_HOST,
        port:CONFIG.API_SERVICE_PORT,
        method:'GET',
        path:url
    };
 
    var req = HTTP.request(
        op,function(res) {
            clearTimeout(requestTimer);
//下面是请求接口数据,得不到回应时,我们关闭等待返回数据的状态,因为有5秒的定时器,
//5秒内如果收到了完整的数据,http模块会自动跳转到res.on('end', function(){})
//因为我们在res.on('end', function(){})的回调函数中clearTimeout(responseTimer),
//清除了这个定时器,所以就不用担心在接受到数据后定时器还反复执行。
            var responseTimer = setTimeout(function () {
                res.destroy();
                debug('......Response Timeout......');
            },5000);
            var recvData = "";
            res.on('data', function(chunk) {
                recvData += chunk;
                // debug(recvData);
            });
            res.on('end', function() {
                clearTimeout(responseTimer);
                if (callback) {
                    callback(null, JSON.parse(recvData));
                }
                debug("请求结束");
            });
        });
    req.on('error', function (e) {
        if (callback) {
            callback(e, null);
        }
    });
 
    req.end();
};

转载地址:https://www.cnblogs.com/yourstars/p/6009368.html

猜你喜欢

转载自www.cnblogs.com/zyulike/p/11495934.html