前置參考
JS執行機制-內存模型(堆內存、棧內存、隊列、執行棧)、事件循環
async/await
示例詳解
示例1
//請寫出輸出內容
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
*/
重點:
- await立即執行等待的內容,將後面的代碼放到微任務中執行
- Promise.then同一層的微任務,按定義順序執行
示例二
async function async1() {
console.log('async1 start');
await async2();
console.log('async1 end');
}
async function async2() {
new Promise(function (resolve) {
console.log('promise1');
resolve();
}).then(function () {
console.log('promise2');
});
}
console.log('script start');
setTimeout(function () {
console.log('setTimeout');
}, 0)
async1();
new Promise(function (resolve) {
console.log('promise3');
resolve();
}).then(function () {
console.log('promise4');
});
console.log('script end');
/*
script start
async1 start
promise1
promise3
script end
promise2
async1 end
promise4
setTimeout
*/
重點:
- Promise.then同一層的微任務,按定義順序執行,不同層的微任務,按層級執行
示例3
async function async1() {
console.log('async1 start');
await async2();
setTimeout(function () {
console.log('setTimeout1')
}, 0)
}
async function async2() {
setTimeout(function () {
console.log('setTimeout2')
}, 0)
}
console.log('script start');
setTimeout(function () {
console.log('setTimeout3');
}, 0)
async1();
new Promise(function (resolve) {
console.log('promise1');
resolve();
}).then(function () {
console.log('promise2');
});
console.log('script end');
/*
script start
async1 start
promise1
script end
promise2
setTimeout3
setTimeout2
setTimeout1
*/
重點:
- setTimeout立即執行,將回調放入宏任務等待執行。所以微任務中的setTimeout也要等待微任務執行時,纔會執行。
- setTimeout按照放入隊列中的順序執行
- 宏任務等待所有已創建的微任務執行完才執行