在下面的代码中,我试图理解编写异步 JavaScript 函数的概念。明确我的假设:
函数 logTest() 被调用。它调用 asyncTest(),传入 log() 函数。但是,asyncTest() 不会直接调用 log()。相反,它将它传递给事件队列,以便在堆栈清除时调用。在 for 循环完成之前,堆栈不应该被清除,写入 20 个“waiting...”。但是,控制台输出将“async”行放在 for 循环之前。我在 Node.js 中运行了这段代码,其中 console.log 是一个同步函数。有谁知道为什么“异步”行没有写在最后?
function asyncCall(method) {
return setTimeout(method, 0);
}
function log(str) { console.log(str); }
function logTest() {
asyncCall(log("async"));
for(var i = 0; i < 20; i++) {
log("waiting...");
}
}
logTest();
最佳答案
那是因为您传递的是log("async")
的结果,而不是函数log
到asyncCall
.
基本上,它执行了 log("async")
(在执行 asyncCall
之前将“async”记录到控制台)。调用的结果(未定义
,因为 log
不返回任何内容)被传递给 asyncCall
。 然后执行异步调用。
您可能希望将其更改为:
asyncCall(log.bind(null, "async"))
或
asyncCall(function(){
log("async");
});
关于javascript - 在 Javascript 中编写异步方法(代码在 Node.js 中运行),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31685670/