[英]Confusion in MicroTask Queue and MacroTask Queue
I am a beginner in JS and While going through Event Loop and Promises
, I came across the below example at mdn
.我是 JS 的初学者,在经历
Event Loop and Promises
时,我在mdn
遇到了以下示例。
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
wait().then(() => console.log(4));
Promise.resolve().then(() => console.log(2)).then(() => console.log(3));
console.log(1); // 1, 2, 3, 4
Shouldn't the O/P be 1,4,2,3
? O/P 不应该是
1,4,2,3
吗?
These are the steps, which according to my understanding should have happened这些是根据我的理解应该发生的步骤
log(1) and then empty the MicroTask Q in the FIFO order. log(1),然后按 FIFO 顺序清空 MicroTask Q。 What am I getting wrong here, please explain
我在这里做错了什么,请解释
The wait
function's promise resolves only after the setTimeout
finishes - after a macrotask (a few milliseconds) In contrast, the Promise.resolve
gets put onto the microtask queue, which will run first (often a millisecond or less). wait
函数的 promise 仅在setTimeout
完成后解析 - 在宏任务(几毫秒)之后,相比之下, Promise.resolve
被放入微任务队列,它将首先运行(通常是一毫秒或更短时间)。 After the console.log(1)
line runs, you'll have the following:在
console.log(1)
行运行后,您将拥有以下内容:
Microtask queue: .then(() => console.log(2)).then(() => console.log(3));
微任务队列:.then
.then(() => console.log(2)).then(() => console.log(3));
Macrotask queue: resolve
(due to the setTimeout
)宏任务队列:
resolve
(由于setTimeout
)
Microtask queue runs first, so 2
gets logged, then the next .then
gets put onto the microtask queue, and 3
gets logged.微任务队列首先运行,所以
2
被记录,然后下一个.then
被放入微任务队列, 3
被记录。 Finally, the setTimeout
macrotask runs, resolving the wait
Promise, putting another .then
onto the microtask queue, and shortly causing 4
to be logged.最后,
setTimeout
宏任务运行,解决了wait
Promise,将另一个.then
放入微任务队列,并很快导致4
被记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.