https://www.jianshu.com/p/51f5fd21588e
async/await是基於promise實現的,他不能用於普通的回調函數
async/await使得異步代碼看起來像同步代碼
async/await與Promise一樣,是非阻塞的。
不同
- 函數前面多了一個
async關鍵字
。await關鍵字只能用在async定義的函數內。async函數會引式返回一個promise,改promise的resolve值就是函數return的值。 -
簡潔
:使用async和await明顯節約了不少代碼,不需要.then,不需要寫匿名函數處理promise的resolve的值,不需要定義多余的data變量,還避免了嵌套代碼。 - async/await讓try/catch 可以同時
處理同步和異步錯誤
。try/catch不能處理JSON.parse的錯誤,因為他在promise中。此時需要.catch,這樣的錯誤處理代碼非常冗余。並且,在我們的實際生產代碼會更加復雜 - 條件語句
下面示例中,需要獲取數據,然后根據返回數據決定是直接返回,還是繼續獲取更多的數據。
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 } }
- 中間值
你很可能遇到過這樣的場景,調用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) }
- 錯誤棧
下面示例中調用了多個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鏈中要好。
- 調試
最后一點,也是非常重要的一點在於,async/await能夠使得代碼調試更簡單。2個理由使得調試Promise變得非常痛苦:
-
不能在返回表達式的箭頭函數中設置斷點
-
如果你在.then代碼塊中設置斷點,使用Step Over快捷鍵,調試器不會跳到下一個.then,因為它只會跳過異步代碼。
使用await/async時,你不再需要那么多箭頭函數,這樣你就可以像調試同步代碼一樣跳過await語句。