首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我混淆了JavaScript宏和微任务优先级

我混淆了JavaScript宏和微任务优先级
EN

Stack Overflow用户
提问于 2022-04-20 06:18:45
回答 1查看 430关注 0票数 3

我读到了JavaScript堆栈中的微任务和宏任务。我写了这段代码:

代码语言: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呢?

EN

回答 1

Stack Overflow用户

发布于 2022-04-20 06:30:24

重要的事情要知道:

  1. 超时为0setTimeout将在下一个事件循环的开头运行该函数。
  2. Promise.resolve.then()中的回调是微任务,将在事件循环当前迭代中的所有宏任务完成后运行。

以下是一个完整的解释:

代码语言:javascript
复制
// 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);

快速列出上面代码发生的顺序:

事件循环的第一次迭代:

  1. Promise.resolve()被称为
  2. 文件底部的setTimeout被调用。队列将在循环的下一次迭代开始时被记录。

-所有宏任务现已完成。转移到微型任务上-

  1. 第一个.then()回调被调用,并且队列中的setTimeout将在事件循环的下一个迭代开始时运行"from承诺一“日志。
  2. 调用第二个.then()回调,并记录"from允诺2“。

事件循环的第二次迭代:

  1. 首先记录"from timeout“,因为它是在前一个事件循环迭代期间排队的第一个宏任务。
  2. “从承诺一”被记录下来。

输出:

代码语言:javascript
复制
from promise two
from timeout
from promise one

查看这个短片,了解事件循环、微任务和宏任务以及JavaScript中的异步编程的简明说明。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71934967

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档