我读到了JavaScript堆栈中的微任务和宏任务。我写了这段代码:
Promise.resolve().then(function () {
setTimeout(function () {
console.log('from promise one');
}, 0);
}).then(() => {
console.log('from promise two');
});
setTimeout(function () {
console.log('from timeout');
}, 0);
但我意识到from timeout在控制台上显示的速度比from promise one快.
据我所知,Promise. then()是一个微任务,在宏任务之前执行,from timeout在这里是一个微任务。但是为什么先执行timeout然后执行Promise. then呢?
发布于 2022-04-20 06:30:24
重要的事情要知道:
0的setTimeout将在下一个事件循环的开头运行该函数。Promise.resolve.then()中的回调是微任务,将在事件循环当前迭代中的所有宏任务完成后运行。以下是一个完整的解释:
// The promise.resolve() runs first.
Promise.resolve()
// Because the function calling the setTimeout is within a .then(), it will
// be called at the END of the CURRENT iteration of the event look.
.then(function () {
// The callback inside this setTimeout will be run at the beginning of the
// next event loop; however it will run after the "from timeout" log, because
// the setTimeout is called AFTER the one at the very bottom of the file.
setTimeout(function () {
console.log('from promise one');
}, 0);
})
.then(() => {
// This log will occur first. No other logs will happen on the beginning of the
// first iteration of the event loop, because everything is being called as
// macro tasks except for this one.
console.log('from promise two');
});
// This setTimeout call runs before the other code above runs. That's because
// it is being called as a macro task for the current iteration of the event
// loop. The callback inside of it, however, will be called at the BEGINNING of
// the NEXT event loop.
setTimeout(function () {
console.log('from timeout');
}, 0);快速列出上面代码发生的顺序:
事件循环的第一次迭代:
Promise.resolve()被称为setTimeout被调用。队列将在循环的下一次迭代开始时被记录。-所有宏任务现已完成。转移到微型任务上-
.then()回调被调用,并且队列中的setTimeout将在事件循环的下一个迭代开始时运行"from承诺一“日志。.then()回调,并记录"from允诺2“。事件循环的第二次迭代:
输出:
from promise two
from timeout
from promise one查看这个短片,了解事件循环、微任务和宏任务以及JavaScript中的异步编程的简明说明。
https://stackoverflow.com/questions/71934967
复制相似问题