ES6/7學習之async/await

  1. async 函數返回一個 Promise 對象,可以使用 then 方法添加回調函數。
  2. async 函數中可能會有 await 表達式,async 函數執行時,如果遇到 await 就會先暫停執行 ,等到觸發的異步操作完成後,恢復 async 函數的執行並返回解析值。
  3. await 操作符用於等待一個 Promise 對象或者任何要等待的值,僅在 async function 中有效。如果在 async function 函數體外使用 await ,你只會得到一個語法錯誤。
  4. 如果一個 Promise 被傳遞給一個 await 操作符,await 將等待 Promise 正常處理完成並返回其處理結果
  5. 如果await等待的不是 Promise 對象,則返回該值本身。
  6. await意味着讓出線程的操作
  7. async會返回Promise對象,如果返回值不是Promise對象則調用Promise.resolve來轉換成Promise對象
  8. 執行棧執行完畢後,會回到隊列中,執行async函數裏後續的語句

如果遇到 await 就會先暫停執行
遇到await依然會執行await等待的內容,然後跳出函數繼續執行同步代碼(讓出線程),執行完再回來繼續執行。

async function async1() {
    console.log('async1');
    await async2();
    console.log('async1 end')
}
async function async2() {
    console.log('async2')
}
async1();
console.log('script end')
/*輸出:
async1
async2
script end
async1 end
*/
async function async1() {
    console.log('async1');
	var num = await 1;
	console.log(num);
    console.log('async1 end')
}
async1();
console.log('script end')
/*輸出:
async1
script end
1
async1 end
*/

await 將等待 Promise 正常處理完成並返回其處理結果
promise狀態未完成,則會一直等待

async function async1() {
    console.log('async1');
    await async2();
    console.log('async1 end')
}
async function async2() {
    console.log('async2')
    return new Promise((resolve,reject)=>{
    	console.log('promise pending')
	})
}
async1();
console.log('script end')
/*輸出:
async1
async2
promise pending
script end
*/
async function async1() {
    console.log('async1');
    await async2();
    console.log('async1 end')
}
async function async2() {
    console.log('async2')
    return new Promise((resolve,reject)=>{
    	console.log('promise pending')
    	resolve(); // 增加了這條
	})
}
async1();
console.log('script end')
/*輸出:
async1
async2
promise pending
script end
async1 end
*/
async function async1() {
    console.log('async1');
    var a = await async2();
    console.log('async1 end')
}
async function async2() {
    console.log('async2')
    return new Promise((resolve,reject)=>{
        console.log('async2 promise')
        resolve();
    }).then(value=>{
        console.log('async2 promise then')
    })
}
async1();
new Promise((resolve,reject)=>{
    console.log('promise')
    resolve();
}).then(value=>{
    console.log('promise then')
})

console.log('script end')
/*輸出:
async1
async2
async2 promise
promise
script end
async2 promise then
promise then
async1 end
*/

參考:
前端er,你真的會用 async 嗎? (此參考中順序示例講解有誤,主要理解原理)
ES6 async 函數

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章