2017-06-16 37 views
0

爲什麼在此示例中請求回調沒有被調用?這 輸出爲:請求回調直到結束纔會被調用

here 
now here 

「做到了!」或者回調中的任何日誌命令都不會被調用。

var request = require('request'); 

d=0; 
console.log("here"); 
request('http://www.google.com', function (error, response, body) { 
    console.log('error:', error); // Print the error if one occurred 
    console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received 
    console.log('body:', body); // Print the HTML for the Google homepage. 
    d=1; 
}); 
console.log("now here"); 
while(d==0){} 
console.log("did it!"); 

如果我刪除「while(d == 0){}」。然後它被調用。

回答

0

你居然卡在while(d==0){}因爲你與同步

使得異步代碼在事件循環的異步代碼大火讓應用程序與同步代碼將觸發while循環,並開始迭代去的流動。

+0

但不是異步調用請求的回調?它應該完成自己,然後調用它的回調?我錯在哪裏? –

+0

是的,但在回到主線程之前,while循環觸發並始終運行。 – abdoutelb

0

您的過程陷入無限循環。

用console.log替換你的d = 1(「did it!」),然後擺脫while循環。

(即你想返回響應後運行一切,你應該把回調函數內)

0

的問題是你的,而在捱餓主線程,傳遞到請求的回調將不會被執行因爲主流將永遠不會執行,所以我建議你研究一下node.js的event loop

這個while循環運行 無限,貪婪地檢查和複覈是永遠不會有機會 發生變化,因爲事件循環是永遠不會有機會來安排你的要求回調 執行值餓死事件循環。