Javascript回调函数未按预期执行 [英] Javascript callback function not executing as intended
问题描述
根据此stackoverflow 回答,
According to this stackoverflow answer,
作为参数传递的函数总是回调,即使意图是同步调用函数...
functions passed as parameters are always callbacks, even if the intention is that the function is called synchronously...
我已经学会了事件循环机制,它基本上说回调函数被推入等待队列并在同步代码完成后执行(堆栈为空),但是在下面的代码中
and I've learned the event loop mechanism which basically says that call back functions are push into a waiting queue and executed after synchronous code finishes(stack empty), however in the following code
function myfun(a, b, callback) {
console.log(a);
callback();
console.log(b);
}
function cb() {console.log('hi')}
myfun(1, 2, cb) // result: 1 hi 2
结果不是 1 2 hi
as我预计,从中我推断只有像 setTimeout
这样的事件信号的回调函数才会被推入这样的队列,但是我找不到支持它的具体参考?
the result is not 1 2 hi
as I expected, from which I infer that only callback functions that fire some 'event signal' like setTimeout
will be pushed into such queue but I can't find concrete reference to support it?
推荐答案
这并不一定意味着每个回调
都是 asynchronous
并且必须放入一些任务队列
并执行一次同步
代码片段(调用堆栈为空)完成。处理 Promise
的回调函数是任务队列
的候选者。例如在你的情况下; cb
函数只是以同步方式运行;所以结果是 1 hi 2
如你所示;但是如果我们修改你的代码如下:
It does not necessarily mean that every a callback
is asynchronous
and must be put into a some task queue
and to be executed once synchronous
code pieces (call stack is empty) finishes. The callback functions dealing with Promise
s are candidates for task queue
. For instance in your case; cb
function simply runs in a synchronous manner; so that the result is 1 hi 2
as you indicated; however if we modify your code as follows:
function myfun(a, b, callback) {
console.log(a);
window.setTimeout(callback, 0);
console.log(b);
}
function cb() {
console.log('hi');
}
myfun(1, 2, cb) // result: 1 2 hi
这将导致 1 2 hi
。即使我将超时设置为 0
毫秒; cb
函数将在 myfun
console.log 之后输出>功能。我建议你看一下 MDN 和这个调用堆栈,事件循环和任务队列的良好解释。希望这会有所帮助。
this will result in 1 2 hi
. Even though I set the timeout to just 0
milliseconds; cb
function will output after the second console.log
within myfun
function. I would recommend you to take a look at MDN and this good explanation of call stack, event loop, and task queues. Hope this helps.
这篇关于Javascript回调函数未按预期执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!