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('script start') let promise1 = new Promise(function (resolve) { console.log('promise1') resolve() console.log('promise1 end') }).then(function () { console.log('promise2') }) setTimeout(function(){ console.log('settimeout') }) console.log('script end') // 輸出順序: script start->promise1->promise1 end->script end->promise2->settimeout
3、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后的函數執行完成並且有了返回結果(Promise對象)之后,才能繼續執行下面的代碼。await通過返回一個Promise對象來實現同步的效果。