js中的宏任务和微任务
异步和同步都是在完成任务列的内容
同步任务是逐条进行的,异步任务有固定时间和非固定时间的
固定时间的异步:setTimeout setInterval requestAnimationFrame(帧时间固定) Promise 非固定时间的:加载文件和加载图片,通信
固定时间的异步中:setTimeOut setInterval 宏任务 Promise 微任务
宏任务的执行:宏任务指将当前的任务挪至下一个任务列的最顶端执行
微任务的执行:微任务将当前任务的内容挪至当前任务列的最底端执行
示例
``new Promise(function (res) {
console.log(1);//---1
res();
Promise.resolve().then(function () {
console.log(2);//---3
});
new Promise(function (res) {
res();
}).then(function () {
console.log(-1);//---4
});
console.log(0);//-----2
})
.then(function () {
console.log(3);//---5
Promise.resolve().then(function () {
console.log(4);//---7
});
})
.then(function () {
console.log(5);//---8
});
Promise.resolve().then(function () {
console.log(6);//---6
Promise.resolve().then(function () {
console.log(7);//----9
});
});
setTimeout(function () {
setTimeout(function () {
console.log(8);//---12
}, 0);
Promise.resolve().then(function () {
console.log(9);//---10
});
}, 0);
setTimeout(function () {
console.log(10);//---11
}, 0);
进行先后执行顺序的判断
- promise中,then之后的是微任务,then之前的是同步任务,先执行同步任务
- 同等级的Promise的转移权重高于then(微任务内的微任务优于微任务执行)
- 找到微任务对应的then
- 找到对应的微任务等级,每个等级都是重新开始转移,和上级无关,不关心下级
- 宏任务的微任务优于微任务的宏任务
new Promise(function(resolve){
resolve();
Promise.resolve().then(function(){
console.log("b");
})
Promise.resolve().then(function(){
console.log("c");
})
}).then(function(){
console.log("a");
})
结果: b c a