Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

宏任务与微任务的优先级; #46

Open
qudawei opened this issue Jun 13, 2024 · 2 comments
Open

宏任务与微任务的优先级; #46

qudawei opened this issue Jun 13, 2024 · 2 comments

Comments

@qudawei
Copy link

qudawei commented Jun 13, 2024

微任务的优先级高于宏任务

@jackchoumine
Copy link

微任务的优先级高于宏任务

博主你好,看到的文章,总结得挺好的。但是我有两个疑问:

1. 把 main script 归到异步任务的宏任务,我理解的 main script 是同步任务,而不是异步任务。不太理解为何把 main script 归为异步任务。

2. 一次事件循环的开始和结束边界在哪,如何判断呢?

比如下面的代码,每个输出语句在第几次事件循环中执行的呢?

console.log(1);

setTimeout(() => {
  console.log(2);
}, 0);

let promise = new Promise((res) => {
  console.log(3);
  resolve();
})
  .then((res) => {
    console.log(4);
  })
  .then((res) => {
    console.log(5);
  });

console.log(6);

// 1 3 6 4 5 2

@xixiIBN5100
Copy link

xixiIBN5100 commented Jul 24, 2024

在一个事件循环内,先执行宏任务,再执行本次宏任务中所有的微任务.script代码段整体是一个宏任务,从上至下执行.输出1以后输出3.console.log(3);虽然在promise里面,但是依然是同步代码,遇到resolve();将.then的内容添加到微任务队列,继续执行console.log(6);,至此本次事件循环中宏任务全部执行完毕,执行微任务中的console.log(4);执行完后将.
then再加入本次宏任务的微任务队列,继续执行console.log(5);.至此本次事件循环中的微任务执行完毕.进行下一轮事件循环,console.log(2);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants