首先分清楚宏任务和微任务
宏任务有:SetTimeout、 setInterval 、Ajax、 Dom
微任务有:promise 、async/await
其中await 只能在async函数中执行
注意:promise中的任务是主进程任务,而.then()中的任务才是微任务,需要假如微任务队列
- 首先执行主进程中的语句,遇到微任务就加入微任务队列,遇到宏任务就加到宏任务队列
- 主进程执行完后,首先执行微任务队列的中语句,然后执行宏任务队列中的语句
- 假如微任务中又有别的任务,那么可以将此微任务中的微任务加入微任务队列,宏任务加到宏任务队列。继续执行第2步。(宏任务队列中的宏任务同理)
注意:通过async定义的函数在调用栈中执行,await 将异步程序变成同步,所以await后面执行的程序需要加入微任务队列中
例如:
async function async1 () {
console.log('async1 start')
await async2();
console.log('async1 end')
}
async function async2 () {
console.log('async2')
}
console.log('script start')
setTimeout(function () {
console.log('setTimeout')
}, 0)
async1();
new Promise (function (resolve) {
console.log('promise1')
resolve();
}).then (function () {
console.log('promise2')
})
console.log('script end')
结果
script start
async1 start
async2
promise1
script end
async1 end
promise2
setTimeout
console.log('script start');
setTimeout(function() {
console.log('setTimeout1');
Promise.resolve().then(function() {
}).then(function() {
console.log('promise5');
setTimeout(function() {
console.log('setTimeout3');
}, 0);
});
}, 0);
Promise.resolve().then(function() {
console.log('promise1');
}).then(function() {
console.log('promise2');
Promise.resolve().then(function() {
console.log('promise3');
}).then(function() {
console.log('promise4');
setTimeout(function() {
console.log('setTimeout2');
}, 0);
});
});
console.log('script end');
结果
script start
script end
promise1
promise2
promise3
promise4
setTimeout1
promise5
setTimeout2
setTimeout3