简体   繁体   English

MicroTask Queue 和 MacroTask Queue 的混淆

[英]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这些是根据我的理解应该发生的步骤

  1. setTimeout CB in MacroTask Q MacroTask Q 中的 setTimeout CB
  2. log(4) CB in MicroTask Q微任务 Q 中的 log(4) CB
  3. log(2) CB in MicroTask Q微任务 Q 中的 log(2) CB
  4. log(3) CB in MicroTask Q微任务 Q 中的 log(3) CB

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM