为什么在事件循环中在宏任务之前执行此微任务

为什么在事件循环中在宏任务之前执行此微任务

本文介绍了为什么在事件循环中在宏任务之前执行此微任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是,在每个宏任务之后 处理完整的微任务任务队列。

My understanding is that the full microtask task queue is processed after each macrotask.

如果是这种情况,为什么 JavaScript Promise 微任务之后,将执行code> setTimeout 回调c>?

If that is the case, why does the setTimeout callback get executed after the Promise microtasks in the following snippet of JavaScript?

console.log('start');

setTimeout(() => {
  console.log("setTimeout");
});

Promise.resolve().then(function() {
  console.log('promise');
});

console.log('end');

这将输出以下内容:

> "start"
> "end"
> "promise"
> "setTimeout"

是因为〜 4ms 现代浏览器带来的延迟?

Is it because of a ~4ms delay imposed by modern browsers?

来自:



Though this states that it is only true for successive callback nesting.

推荐答案

是。以及您运行的代码,从 console.log('start') console.log('end')就是这样的宏任务。运行完毕后,将处理带有promise回调的微任务队列,只有在下一个宏任务(超时)开始运行之后。

Yes. And the code that you ran, from console.log('start') to console.log('end'), is such a macrotask. After it ran to completion, the microtask queue with the promise callbacks is processed, and only after that the next macrotask (the timeout) gets to run.

这篇关于为什么在事件循环中在宏任务之前执行此微任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 11:15