前言
Node.js 7.6 已經(jīng)支持 async/await 了,如果你還沒(méi)有試過(guò),這篇博客將告訴你為什么要用它。
Async/Await 簡(jiǎn)介
對(duì)于從未聽(tīng)說(shuō)過(guò) async/await 的朋友,下面是簡(jiǎn)介:
Async/Await 語(yǔ)法
示例中,getJSON 函數(shù)返回一個(gè) promise,這個(gè) promise 成功 resolve 時(shí)會(huì)返回一個(gè) json 對(duì)象。我們只是調(diào)用這個(gè)函數(shù),打印返回的 JSON 對(duì)象,然后返回”done”。
使用 Promise 是這樣的:
const makeRequest = () =>getJSON().then(data => {console.log(data);return "done";});makeRequest();使用 Async/Await 是這樣的:
const makeRequest = async () => {console.log(await getJSON());return "done";};makeRequest();它們有一些細(xì)微不同:
函數(shù)前面多了一個(gè) async 關(guān)鍵字。await 關(guān)鍵字只能用在 async 定義的函數(shù)內(nèi)。async 函數(shù)會(huì)隱式地返回一個(gè) promise,該 promise 的 reosolve 值就是函數(shù) return 的值。(示例中 reosolve 值就是字符串”done”)
第 1 點(diǎn)暗示我們不能在最外層代碼中使用 await,因?yàn)椴辉?async 函數(shù)內(nèi)。
// 不能在最外層代碼中使用awaitawait makeRequest();// 這是會(huì)出事情的makeRequest().then(result => {// 代碼});await getJSON()表示 console.log 會(huì)等到 getJSON 的 promise 成功 reosolve 之后再執(zhí)行。
為什么 Async/Await 更好?
1. 簡(jiǎn)潔
由示例可知,使用 Async/Await 明顯節(jié)約了不少代碼。我們不需要寫(xiě).then,不需要寫(xiě)匿名函數(shù)處理 Promise 的 resolve 值,也不需要定義多余的 data 變量,還避免了嵌套代碼。這些小的優(yōu)點(diǎn)會(huì)迅速累計(jì)起來(lái),這在之后的代碼示例中會(huì)更加明顯。
2. 錯(cuò)誤處理
Async/Await 讓 try/catch 可以同時(shí)處理同步和異步錯(cuò)誤。在下面的 promise 示例中,try/catch 不能處理 JSON.parse 的錯(cuò)誤,因?yàn)樗?Promise 中。我們需要使用.catch,這樣錯(cuò)誤處理代碼非常冗余。并且,在我們的實(shí)際生產(chǎn)代碼會(huì)更加復(fù)雜。
const makeRequest = () => {try {getJSON().then(result => {// JSON.parse可能會(huì)出錯(cuò)const data = JSON.parse(result);console.log(data);});// 取消注釋,處理異步代碼的錯(cuò)誤// .catch((err) => {// console.log(err)// })} catch (err) {console.log(err);}};使用 async/await 的話,catch 能處理 JSON.parse 錯(cuò)誤:
const makeRequest = async () => {try {// this parse may failconst data = JSON.parse(await getJSON());console.log(data);} catch (err) {console.log(err);}};3. 條件語(yǔ)句
下面示例中,需要獲取數(shù)據(jù),然后根據(jù)返回?cái)?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 層),括號(hào),return 語(yǔ)句很容易讓人感到迷茫,而它們只是需要將最終結(jié)果傳遞到最外層的 Promise。
上面的代碼使用 async/await 編寫(xiě)可以大大地提高可讀性:
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. 中間值
你很可能遇到過(guò)這樣的場(chǎng)景,調(diào)用 promise1,使用 promise1 返回的結(jié)果去調(diào)用 promise2,然后使用兩者的結(jié)果去調(diào)用 promise3。你的代碼很可能是這樣的:
const makeRequest = () => {return promise1().then(value1 => {return promise2(value1).then(value2 => {return promise3(value1, value2);});});};如果 promise3 不需要 value1,可以很簡(jiǎn)單地將 promise 嵌套鋪平。如果你忍受不了嵌套,你可以將 value 1 & 2 放進(jìn) Promise.all 來(lái)避免深層嵌套:
const makeRequest = () => {return promise1().then(value1 => {return Promise.all([value1, promise2(value1)]);}).then(([value1, value2]) => {return promise3(value1, value2);});};這種方法為了可讀性犧牲了語(yǔ)義。除了避免嵌套,并沒(méi)有其他理由將 value1 和 value2 放在一個(gè)數(shù)組中。
使用 async/await 的話,代碼會(huì)變得異常簡(jiǎn)單和直觀。
const makeRequest = async () => {const value1 = await promise1();const value2 = await promise2(value1);return promise3(value1, value2);};5. 錯(cuò)誤棧
下面示例中調(diào)用了多個(gè) Promise,假設(shè) Promise 鏈中某個(gè)地方拋出了一個(gè)錯(cuò)誤:
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)});Promise 鏈中返回的錯(cuò)誤棧沒(méi)有給出錯(cuò)誤發(fā)生位置的線索。更糟糕的是,它會(huì)誤導(dǎo)我們;錯(cuò)誤棧中唯一的函數(shù)名為 callAPromise,然而它和錯(cuò)誤沒(méi)有關(guān)系。(文件名和行號(hào)還是有用的)。
然而,async/await 中的錯(cuò)誤棧會(huì)指向錯(cuò)誤所在的函數(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)});在開(kāi)發(fā)環(huán)境中,這一點(diǎn)優(yōu)勢(shì)并不大。但是,當(dāng)你分析生產(chǎn)環(huán)境的錯(cuò)誤日志時(shí),它將非常有用。這時(shí),知道錯(cuò)誤發(fā)生在 makeRequest 比知道錯(cuò)誤發(fā)生在 then 鏈中要好。
6. 調(diào)試
最后一點(diǎn),也是非常重要的一點(diǎn)在于,async/await 能夠使得代碼調(diào)試更簡(jiǎn)單。2 個(gè)理由使得調(diào)試 Promise 變得非常痛苦:
不能在返回表達(dá)式的箭頭函數(shù)中設(shè)置斷點(diǎn)
如果你在.then 代碼塊中設(shè)置斷點(diǎn),使用 Step Over 快捷鍵,調(diào)試器不會(huì)跳到下一個(gè).then,因?yàn)樗粫?huì)跳過(guò)異步代碼。
使用 await/async 時(shí),你不再需要那么多箭頭函數(shù),這樣你就可以像調(diào)試同步代碼一樣跳過(guò) await 語(yǔ)句。
結(jié)論
Async/Await 是近年來(lái) JavaScript 添加的最革命性的特性之一。它會(huì)讓你發(fā)現(xiàn) Promise 的語(yǔ)法有多糟糕,而且提供了一個(gè)直觀的替代方法。
憂慮
對(duì)于 Async/Await,也許你有一些合理的懷疑:
它使得異步代碼不再明顯: 我們已經(jīng)習(xí)慣了用回調(diào)函數(shù)或者.then 來(lái)識(shí)別異步代碼,我們可能需要花數(shù)個(gè)星期去習(xí)慣新的標(biāo)志。但是,C#擁有這個(gè)特性已經(jīng)很多年了,熟悉它的朋友應(yīng)該知道暫時(shí)的稍微不方便是值得的。
Node 7 不是 LTS(長(zhǎng)期支持版本): 但是,Node 8 下個(gè)月就會(huì)發(fā)布,將代碼遷移到新版本會(huì)非常簡(jiǎn)單。(Fundebug 注:Node 8 是 LTS,已經(jīng)于 2017 年 10 月正式發(fā)布。)
原文: 6 Reasons Why JavaScript's Async/Await Blows Promises Away
譯者: Fundebug
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注