【发布时间】:2016-12-22 07:38:49
【问题描述】:
我创建了一个小脚本来更好地理解回调。
从下面的脚本中,我预期的行为是:“http.get 运行并平均需要 200 毫秒。for 循环“i”增量平均需要 2500 毫秒。在 200 毫秒时,进程应该退出并且脚本应该停止工作。为什么它打印所有的 i?如果我更好地理解这一点,我想我理解回调。
var http = require("http");
var starttime = new Date();
//Function with Callback
for (var j =0; j<10; j++){
http.get({host : 'nba.com'}, function(res){
console.log("Time Taken = ", new Date() - starttime, 'ms');
process.exit();
}).on('error', function(er){
console.log('Got Error :', er.message);
})
}
//Loop that exceeds callback trigger time
for(var i=1; i<10000; i++){
console.log(i);
}
console.log("Time Taken = ", new Date() - starttime, 'ms');
【问题讨论】:
-
for循环是同步的,里面的代码是异步的。它通过触发 get async get 调用的 for 循环运行。 for 循环在 on 回调被触发之前退出。互联网上有大量文档和示例来说明异步的工作原理。
-
谢谢布赖恩马克。我会检查他们。现在清如云。
标签: node.js callback asynccallback