JS执行机制
JS优先执行同步任务,异步任务会被放入特定的处理程序中满足条件后,被放到消息(任务/事件)队列中,同步队列完成后再来执行消息队列中的事件。 同步任务 > 异步任务,异步任务又分为微任务 > 宏任务。
微任务和宏任务
我们主要关注常用的微任务,也就是Promise,宏任务主要记的就是定时器,执行顺序最低。
微任务中的Promise、async、await
Promise中,只有then里面的是放入微任务,async、await只有await下一行的放入微任务,紧跟await后面的事件立即执行。具体看下面代码:
console.log('外部任务1');
new Promise((resolve, reject) => {
console.log('Promise1')
resolve()
console.log('Promise2')
}).then(res => {
console.log('Promise.then1')
})
async function async1(){
console.log('async1')
await fn()
console.log('await1')
}
function fn() {
console.log('fn1')
}
setTimeout(() => {
console.log('setTimeout1')
}, 0)
async1()
fn()
console.log('外部任务2')
// 执行结果:外部任务1,Promise1, Promise2, async1, fn1, fn1, 外部任务2, Promise.then1, await1, setTimeout1
这里主要注意 Promise中的 2,3是马上执行的,只有then里面的会作为微任务处理,而 async 中 5 等同于Promise中的 2,3,需要注意的是 await 后面的事件是马上执行的,如果事件里面有同步任务则会马上执行,也就是 console.log(7)会马上执行。