浏览器中并不存在宏任务,宏任务(Macrotask)是 Node.js 发明的术语。
浏览器中只有任务(Task)和微任务(Microtask)。
- 使用 script 标签、setTimeout 可以创建任务。
- 使用 Promise#then、window.queueMicrotask、MutationObserver、Proxy 可以
创建微任务。
执行顺序?
微任务会在任务间隙执行(俗称插队执行)。
注意,微任务不能插微任务的队,微任务只能插任务的队
面试题:
Promise.resolve()
.then(() => {
console.log(0);
return Promise.resolve('4x');
})
.then((res) => {console.log(res)})
Promise.resolve().then(() => {console.log(1);})
.then(() => {console.log(2);}, ()=>{console.log(2.1)})
.then(() => {console.log(3);})
.then(() => {console.log(5);})
.then(() => {console.log(6);})
//0 1 2 3 4x 5 6
注意,多个 then 里面的回调并不会一次性插入等待队列中,而是执行完一个再插入下一个。