nodejs http 請求延時的處理方法(防止程式崩潰)

來源:互聯網
上載者:User

標籤:bug   程式   java   方法   定時器   log   清除   程式崩潰   error   

有時候因為介面沒開,或者其他原因,導致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();};

  

  

nodejs http 請求延時的處理方法(防止程式崩潰)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.