浏览器里的微任务和任务是什么?
浏览器中并不存在宏任务,宏任务(Macrotask)是 Node.js 发明的术语。
浏览器中只有任务(Task)和微任务(Microtask)。
使用 script 标签、setTimeout 可以创建任务。
使用 Promise#then、window.queueMicrotask、MutationObserver、Proxy 可以创建微任务。
执行顺序是怎样的呢?
微任务会在任务间隙执行(俗称插队执行)。
⚠️
注意,微任务不能插微任务的队,微任务只能插任务的队。
面试题:
// next = [0, 4x, 1, 2, 3, 5, 6]
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);})
Last updated
