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