宏队列:dom事件回调、ajax事件回调、定时器回调
微队列:promise回调、mutation回调
如对上述名词有不理解之处,请自行上MDN官方文档查询
为了方便起见,代码行由最终的输出指定,如1代表第二行代码,2代表第五行代码。
第一题
setTimeout(() => {
console.log(1);
}, 0)
Promise.resolve().then(() => {
console.log(2);
})
Promise.resolve().then(() => {
console.log(4);
})
console.log(3);
解析:promise为微队列,setTimeOut为宏队列,均为异步。先执行同步调用的最后一行代码。再执行2、4,最后执行1。
所以对应的执行顺序为:3、2、4、1
第二题
setTimeout(() => {
console.log(1);
}, 0)
new Promise((resolve) => {
console.log(2);
resolve()
}).then(() => {
console.log(3);
}).then(() => {
console.log(4);
})
console.log(5);
分析:
宏队列:[1]
微队列:[3、4]
同步执行:[2、5]
所以对应的执行顺序为:2、5、3、4、1
第三题
const first = () => (new Promise((resolve, reject) => {
console.log(3);
let p = new Promise((resolve, reject) => {
console.log(7);
setTimeout(() => {
console.log(5);
resolve(6)
}, 0);
resolve(1)
})
resolve(2)
p.then((arg) => {
console.log(arg);
})
}))
first().then((arg) => {
console.log(arg);
})
console.log(4);
分析:
宏队列:[5]
微队列:[1、2]
同步执行:[3、7、4]
所以对应的执行顺序为:3、7、4、1、2、5
第四题
setTimeout(() => {
console.log("0");
}, 0);
new Promise((resolve, reject) => {
console.log("1");
resolve()
}).then(() => {
console.log("2");
new Promise((resolve, reject) => {
console.log("3");
resolve()
}).then(() => {
console.log("4");
}).then(() => {
console.log("5");
})
}).then(() => {
console.log("6");
})
new Promise((resolve, reject) => {
console.log("7");
resolve()
}).then(() => {
console.log("8");
})
分析:
宏队列:[0]
微队列:[2、3、8、4、6、5]
同步执行:[1、7]
所以对应的执行顺序为1、7、2、3、8、4、6、5、0