2017-06-16 56 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循环运行 无限,贪婪地检查和复核是永远不会有机会 发生变化,因为事件循环是永远不会有机会来安排你的要求回调 执行值饿死事件循环。