ES7 引入的 async/await 是 JavaScript 異步編程的一個重大改進,提供了在不阻塞主線程的情況下使用同步代碼異步訪問資源的能力。在本文中,我們將從不同的角度探索 async/await,并演示如何正確有效地使用它們。 async/await 的好處async/await 給我們帶來的最重要的好處是同步編程風格。我們來看一個例子。 // async/awaitasync getBooksByAuthorWithAwait(authorId) { const books = await bookModel.fetchAll(); return books.filter(b => b.authorId === authorId);}// promisegetBooksByAuthorWithPromise(authorId) { return bookModel.fetchAll() .then(books => books.filter(b => b.authorId === authorId));}很顯然,async/await 比 promise 更容易理解。如果忽略掉 await 關鍵字,代碼看起來與其他任意一門同步語言一樣(如 Python)。 除了可讀性,async/await 還對瀏覽器提供了原生支持。目前所有的主流瀏覽器都完全支持異步功能。 原生支持意味著不需要編譯代碼。更重要的是,它調試起來很方便。在函數入口設置斷點并執行跳過 await 行之后,調試器會在 bookModel.fetchAll() 執行時暫停一會兒,然后移動到下一行(也就是.filter)!這比使用 promise 要容易調試得多,因為你必須在.filter 這一行設置另一個斷點。 另一個好處是 async 關鍵字,盡管看起來不是很明顯。它聲明 getBooksByAuthorWithAwait() 函數的返回值是一個 promise,因此調用者可以安全地調用 getBooksByAuthorWithAwait().then(…) 或 await getBooksByAuthorWithAwait()。比如像下面這段代碼: getBooksByAuthorWithPromise(authorId) { if (!authorId) { return null; } return bookModel.fetchAll() .then(books => books.filter(b => b.authorId === authorId)); }}在上面的代碼中,getBooksByAuthorWithPromise 可能返回一個 promise(正常情況)或 null(異常情況),在這種情況下,調用者無法安全地調用.then()。而如果使用 async 聲明,則不會出現這種情況。 async/await 可能會引起誤解有些文章將 async/await 與 promise 進行了比較,并聲稱它是 JavaScript 異步編程演變的下一代,但我非常不同意這一觀點。async/await 是一種改進,但它不過是一種語法糖,它不會完全改變我們的編程風格。 從本質上講,異步函數仍然是 promise。在正確使用異步函數之前,你必須了解 promise,更糟糕的是,大部分時間需要同時使用 promise 和異步函數。 考慮上例中的 getBooksByAuthorWithAwait() 和 getBooksByAuthorWithPromises() 函數。請注意,它們不僅功能相同,接口也是完全一樣的! 這意味著如果直接調用 getBooksByAuthorWithAwait(),它將返回一個 promise。 不過這不一定是件壞事。只是 await 會給人一種感覺:“它可以將異步函數轉換為同步函數”。但這實際上是錯誤的。 async/await 的陷阱那么人們在使用 async/await 時可能會犯什么錯誤?下面列舉了一些常見的錯誤。 太過串行化雖然 await 可以讓你的代碼看起來像是同步的,但請記住,它們仍然是異步的,要避免太過串行化。 async getBooksAndAuthor(authorId) { const books = await bookModel.fetchAll(); const author = await authorModel.fetch(authorId); return { author, books: books.filter(book => book.authorId === authorId), };}上面的代碼在邏輯上看起來很正確,但這樣做其實是不對的。 注意,authorModel.fetch(authorId) 不依賴 bookModel.fetchAll() 的結果,事實上它們可以并行調用!然而,因為在這里使用了 await,兩個調用變成串行的,總的執行時間將比并行版本要長得多。 正確的方法應該是: async getBooksAndAuthor(authorId) { const bookPromise = bookModel.fetchAll(); const authorPromise = authorModel.fetch(authorId); const book = await bookPromise; const author = await authorPromise; return { author, books: books.filter(book => book.authorId === authorId), };}或者更糟糕的是,如果你想要逐個獲取物品清單,你必須使用 promise: async getAuthors(authorIds) { // WRONG, this will cause sequential calls // const authors = _.map( // authorIds, // id => await authorModel.fetch(id));// CORRECT const promises = _.map(authorIds, id => authorModel.fetch(id)); const authors = await Promise.all(promises);}總之,你仍然需要將流程視為異步的,然后使用 await 寫出同步的代碼。在復雜的流程中,直接使用 promise 可能更方便。 錯誤處理在使用 promise 時,異步函數有兩個可能的返回值。對于正常情況,可以使用.then(),而對于異常情況,則使用.catch()。不過在使用 async/await 時,錯誤處理可能會變得有點蹊蹺。 try…catch最標準的(也是我推薦的)方法是使用 try…catch 語句。在調用 await 函數時,如果出現非正常狀況就會跑出異常。比如: class BookModel { fetchAll() { return new Promise((resolve, reject) => { window.setTimeout(() => { reject({'error': 400}) }, 1000); }); }}// async/awaitasync getBooksByAuthorWithAwait(authorId) {try { const books = await bookModel.fetchAll();} catch (error) { console.log(error); // { "error": 400 }}在捕捉到異常之后,我們有幾種方法來處理它: 處理異常,并返回一個正常值。(不在 catch 塊中使用任何 return 語句相當于使用 return undefined,undefined 也是一個正常值。) 如果你想讓調用者來處理它,就將它拋出。你可以直接拋出錯誤對象,比如 throw error,這樣就可以在 promise 鏈中使用 await getBooksByAuthorWithAwait() 函數(也就是像 getBooksByAuthorWithAwait().then(...).catch(error => …) 這樣調用它)。或者你可以將錯誤包裝成 Error 對象,比如 throw new Error(error),那么在控制臺中顯示這個錯誤時它將給出完整的堆棧跟蹤信息。 拒絕它,比如 return Promise.reject(error)。這相當于 throw error,因此不推薦使用。
這種方法也有一個缺陷。由于 try...catch 會捕獲代碼塊中的每個異常,所以通常不會被 promise 捕獲的異常也會被捕獲到。比如: class BookModel { fetchAll() { cb(); // note `cb` is undefined and will result an exception return fetch('/books'); }}try { bookModel.fetchAll();} catch(error) { console.log(error); // This will print "cb is not defined"}運行此代碼,你將會在控制臺看到“ReferenceError:cb is not defined”錯誤,消息的顏色是黑色的。錯誤消息是通過 console.log() 輸出的,而不是 JavaScript 本身。有時候這可能是致命的:如果 BookModel 被包含在一系列函數調用中,并且其中一個調用把錯誤吞噬掉了,那么找到這樣的 undefined 錯誤將非常困難。 讓函數返回兩個值錯誤處理的另一種方式是受到了 Go 語言啟發,它允許異步函數返回錯誤和結果。 簡單地說,我們可以像這樣使用異步函數: [err, user] = await to(UserModel.findById(1));我個人不喜歡這種方法,因為它將 Go 語言的風格帶入到了 JavaScript 中,感覺不自然。但在某些情況下,這可能相當有用。 使用.catch我們要介紹的最后一種方法是繼續使用.catch()。 回想一下 await 的功能:它將等待 promise 完成工作。另外,promise.catch() 也會返回一個 promise!所以我們可以這樣進行錯誤處理: // books === undefined if error happens,// since nothing returned in the catch statementlet books = await bookModel.fetchAll() .catch((error) => { console.log(error); });這種方法有兩個小問題: 結論ES7 引入的 async/await 關鍵字絕對是對 JavaScript 異步編程的重大改進。它讓代碼更易于閱讀和調試。然而,要正確使用它們,人們必須了解 promise。它們不過是語法糖,本質上仍然是 promise。
|