目錄
- 含義
- 使用
- 串行 & 并行
含義
async
- async函式回傳一個 Promise 物件
- async函式是 Generator 函式的語法糖
- async函式內部return陳述句回傳的值,會成為then方法回呼函式的引數,
- async函式內部拋出錯誤,會導致回傳的 Promise 物件變為reject狀態,拋出的錯誤物件會被catch方法回呼函式接收到,
await
- await只能作用在async修飾的方法中
- await命令后面是一個 Promise 物件,回傳該物件成功的結果,如果不是 Promise 物件,就直接回傳對應的值,
- await命令后面的 Promise 物件如果變為reject狀態,則會被catch方法的回呼函式接收到,
- await是會阻塞代碼執行
await命令后面的Promise物件,運行結果可能是rejected,所以最好把await命令放在try…catch代碼塊中,
使用
var timer1 = () => new Promise((resolve, reject) => {
setTimeout(()=>{
console.log('2秒后...')
reject('2秒已過,報錯')
},2000)
})
var fn = async () => {
const a = 123
await timer1() // await阻塞代碼執行,2秒后再直接進行報錯捕獲
console.log('again') // 不執行
}
fn().then(res=>{
console.log(res);
}).catch(err=>{ // 在return 前面有報錯,catch捕獲
console.log(err); // 捕獲reject --> 2秒已過,報錯
})
串行 & 并行
var timer2 = () => new Promise((resolve, reject) => {
setTimeout(()=>{
console.log(2)
resolve(2)
},2000)
})
var timer3 = () => new Promise((resolve, reject) => {
setTimeout(()=>{
console.log(3)
resolve(3)
},3000)
})
// 串行
async function f() {
var num3 = await timer3() // 先走3秒
console.log('3秒走完中途執行log',111) // 阻塞代碼執行了,先走完3秒,再log 111
var num2 = await timer2() // 再走2秒
return num3 + num2 // 總 5秒后return 3 + 2
}
f().then(res=>console.log(res)) // 5
// 并行 (可提高代碼加載性能)
// 也可以使用Promise.all() 方法,效果更佳
async function f() {
var num2 = timer2() // 提前執行
var num3 = timer3() // 提前執行
await num2 // 先走2秒
await num3 // 再走了1秒
return num2 + num3 // 總3秒
}
f().then(res=>console.log(res)) // 3秒后return 5
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/304946.html
標籤:其他
上一篇:超鏈接的5種表現形式(用法)
