1. setTimeout
console.log('script start') //1. 打印 script start
setTimeout(function(){
console.log('settimeout') // 4. 打印 settimeout
}) // 2. 調用 setTimeout 函數,並定義其完成后執行的回調函數
console.log('script end') //3. 打印 script start
// 輸出順序:script start->script end->settimeout
2. Promise
Promise本身是同步的立即執行函數, 當在executor中執行resolve或者reject的時候, 此時是異步操作, 會先執行then/catch等,當主棧完成后,才會去調用resolve/reject中存放的方法執行,打印p的時候,是打印的返回結果,一個Promise實例。
console.log('promise111')
let promise1 = new Promise(function (resolve) {
console.log('promise222')
resolve()
console.log('promise333')
}).then(function () {
console.log('promise555')
})
setTimeout(function () {
console.log('promise666')
})
console.log('promise444')
// 3. async/await
async function async1() {
console.log('async022');
await async2();
console.log('async055')
}
async function async2() {
console.log('async033')
}
console.log('async011');
async1();
console.log('async044')
// 輸出順序:script start->async1 start->async2->script end->async1 end
// async 函數返回一個 Promise 對象,當函數執行的時候,一旦遇到 await 就會先返回,等到觸發的異步操作完成,再執行函數體內后面的語句。可以理解為,是讓出了線程,跳出了 async 函數體。