setTimeout属性宏任务,Promise里面的then方法属于微任务,Async/Await中await语法后面紧跟的表达式是同步的,但接下来的代码是异步的,属于微任务。
同步--异步--微任务--宏任务
宏任务优先级
主代码块 > setImmediate > MessageChannel > setTimeout / setInterval
微任务优先级
微任务microtask:process.nextTick > Promise = MutationObserver
setTimeout
console.log("script start");
setTimeout(function () {
console.log('setTimeout')
}, 0);
console.log('script end');
输出:script start-->script end-->setTimeout
Promise:
Promise本身是同步的,但在执行resolve或者rejects时是异步的,即then方法是异步的。
console.log("start");
let promise1 = new Promise(function(resolve) {
console.log("111");
resolve();
console.log("111 end");
}).then(function(){
console.log('222');
})
setTimeout(function () {
console.log('setTimeout');
}, 0)
console.log('end');
输出:start-->111-->>111end-->end-->222-->setTimeout
async/await:
async function async1(){
console.log('async1 start');
await async2();
console.log('async1 end')
}
async function async2(){
console.log('async2')
}
console.log('script start');
async1();
console.log('script end')
输出顺序:script start -> async1 start -> async2 -> script end -> async1 end
async 函数返回一个 Promise 对象,当函数执行的时候,一旦遇到 await 就会先返回,等到触发的异步操作完成,再执行函数体内后面的语句。可以理解为,是让出了线程,跳出了 async 函数体。
await后面跟一个表达式,async方法执行时,遇到await后会立即执行表达式,然后把表达式后边的代码放到微任务队列中,让出执行栈让同步代码先执行;