浏览器里的微任务和任务是什么?
浏览器中并不存在宏任务,宏任务(Macrotask)是 Node.js 发明的术语。
浏览器中只有任务(Task)和微任务(Microtask)
使用 script 标签、setTimeout 可以创建任务。
使用 Promise#then、window.queueMicrotask、MutationObserver、Proxy 可以创建微任务
执行顺序是怎样的呢?
微任务会在任务间隙执行(俗称插队执行)。
注意,微任务不能插微任务的队,微任务只能插任务的队。
面试题:
为什么以下代码的返回结果是 0 1 2 3 4 5 6 而不是 0 1 2 4 3 5 6?
Promise.resolve()
.then(() => {
console.log(0);
return Promise.resolve('4x'); // return Promise.resolve(...) 等于两个 then
})
.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 (4x 后移两个) 2 3 (最终 4x) 5 6
宏任务对列(最后执行):
最终执行:0 1 2 3 4x 5 6