Async/Await簡介
- async/await是寫異步代碼的新方式躏尉,以前的方法有回調(diào)函數(shù)和Promise。
- async/await是基于Promise實現(xiàn)的规阀,它不能用于普通的回調(diào)函數(shù)台汇。
- async/await與Promise一樣,是非阻塞的啦撮。
- async/await使得異步代碼看起來像同步代碼,這正是它的魔力所在汪厨。
Async/Await語法
Promise寫法:
const makeRequest = () =>
getJSON()
.then(data => {
console.log(data)
return "done"
})
makeRequest()
Async/Await寫法:
const makeRequest = async () => {
console.log(await getJSON())
return "done"
}
makeRequest()
示例中赃春,getJSON函數(shù)返回一個promise,這個promise成功resolve時會返回一個promise對象劫乱。我們只是調(diào)用這個函數(shù)织中,打印返回的JSON對象,然后返回“done”衷戈。
它們有一些細微不同:
- 函數(shù)前面多了一個async關(guān)鍵字狭吼。await關(guān)鍵字只能用在async定義的函數(shù)內(nèi)。async函數(shù)會隱式的返回一個promise殖妇,該promise的resolve值就是函數(shù)return的值刁笙。(示例中resolve值就是字符串"done")
- 第1點暗示我們不能在最外層代碼中使用await,因為不在async函數(shù)內(nèi)谦趣。
//不能在最外層代碼中使用await
await makeRequest()
//這是會出事的
makeRequest().then((result) => {
//代碼
})
await getJSON()表示console.log會等到getJSON的promise成功reosolve之后再執(zhí)行疲吸。
為什么Async/Await更好?
1. 簡潔
由示例可知前鹅,使用Async/Await明顯節(jié)約了不少代碼摘悴。我們不需要寫.then,不需要寫匿名函數(shù)處理Promise的resolve值舰绘,也不需要定義多余的data變量蹂喻,還避免了嵌套代碼。這些小的優(yōu)點會迅速累計起來捂寿,這在之后的代碼示例中會更加明顯口四。
2. 錯誤處理
Async/Await讓try/catch可以同時處理同步和異步錯誤。在下面的promise示例中者蠕,try/catch不能處理JSON.parse的錯誤窃祝,因為它在Promise中。我們需要使用.catch踱侣,這樣錯誤處理代碼非常冗余粪小。并且,在我們的實際生產(chǎn)代碼會更加復雜抡句。
const makeRequest = () => {
try {
getJSON()
.then(result => {
// JSON.parse可能會出錯
const data = JSON.parse(result)
console.log(data)
})
// 取消注釋探膊,處理異步代碼的錯誤
// .catch((err) => {
// console.log(err)
// })
} catch (err) {
console.log(err)
}
}
使用aync/await的話,catch能處理JSON.parse錯誤:
const makeRequest = async () => {
try {
// this parse may fail
const data = JSON.parse(await getJSON())
console.log(data)
} catch (err) {
console.log(err)
}
}
3. 條件語句
下面示例中待榔,需要獲取數(shù)據(jù)逞壁,然后根據(jù)返回數(shù)據(jù)決定是直接返回,還是繼續(xù)獲取更多的數(shù)據(jù)锐锣。
const makeRequest = () => {
return getJSON()
.then(data => {
if (data.needsAnotherRequest) {
return makeAnotherRequest(data)
.then(moreData => {
console.log(moreData)
return moreData
})
} else {
console.log(data)
return data
}
})
}
上面的代碼嵌套(6層)腌闯、括號、return語句很容易讓人看不懂雕憔。
使用Async/Await編寫:
const makeRequest = async () => {
const data = await getJSON()
if (data.needsAnotherRequest) {
const moreData = await makeAnotherRequest(data);
console.log(moreData)
return moreData
} else {
console.log(data)
return data
}
}
4. 中間值
你可能遇到過這樣的場景姿骏,調(diào)用promise1,使用promise1返回的結(jié)果調(diào)用promise2斤彼,然后使用兩者的結(jié)果調(diào)用promise3分瘦。使用promise的代碼是:
const makeRequest = () => {
return promise1()
.then(value1 => {
return promise2(value1)
.then(value2 => {
return promise3(value1, value2)
})
})
}
如何promise3不使用value1,可以很簡單的將promise鋪平琉苇。如果忍受不了嵌套嘲玫,可以將value1 & value2放進Promise.all來避免深層嵌套:
const makeRequest = () => {
return promise1()
.then(value1 => {
return Promise.all([value1, promise2(value1)])
})
.then(([value1, value2]) => {
return promise3(value1, value2)
})
}
這種方法為了可讀性犧牲了語義,除了避免嵌套并扇,并沒有其他理由將value1和value2放在一個數(shù)組中去团。
使用async/await的話,代碼會變得異常簡單和直觀:
const makeRequest = async () => {
const value1 = await promise1()
const value2 = await promise2(value1)
return promise3(value1, value2)
}
5. 錯誤棧
const makeRequest = () => {
return callAPromise()
.then(() => callAPromise())
.then(() => callAPromise())
.then(() => callAPromise())
.then(() => callAPromise())
.then(() => {
throw new Error("oops");
})
}
makeRequest()
.catch(err => {
console.log(err);
// output
// Error: oops at callAPromise.then.then.then.then.then (index.js:8:13)
})
上述示例中調(diào)用了多個promise穷蛹,假設(shè)promise鏈中某個地方拋出了一個異常渗勘,返回的錯誤棧沒有給出錯誤發(fā)生的位置信息。
async/await中的錯誤棧會指向錯誤所在的函數(shù):
const makeRequest = async () => {
await callAPromise()
await callAPromise()
await callAPromise()
await callAPromise()
await callAPromise()
throw new Error("oops");
}
makeRequest()
.catch(err => {
console.log(err);
// output
// Error: oops at makeRequest (index.js:7:9)
})
在開發(fā)過程中俩莽,可能這一點優(yōu)勢并不是很大旺坠。但是,如果是分析生產(chǎn)環(huán)境的錯誤日志時扮超,它將非常有用取刃。
6. 調(diào)試
async/await能夠使代碼更方便調(diào)試。
promise調(diào)試非常痛苦:
- 不能在返回表達式的箭頭函數(shù)中設(shè)置斷點
const makeRequest = () => {
return callAPromise()
.then(() => callAPromise())
.then(() => callAPromise())
.then(() => callAPromise())
.then(() => callAPromise())
}
- 如果在.then代碼塊中設(shè)置斷點出刷,使用Step Over快捷鍵璧疗,調(diào)試器不會調(diào)到下一個.then,因為它只會跳過異步代碼馁龟。
使用async/await時崩侠,不再需要那么多箭頭函數(shù),這樣就可以像調(diào)試同步代碼一樣跳過await語句坷檩。
const makeRequest = async () => {
await callAPromise()
await callAPromise()
await callAPromise()
await callAPromise()
}