詳解JavaScript中async/await的使用方法

2020-11-19 21:00:53

ES8 引入的 async/await 在 JavaScript 的非同步程式設計中是一個極好的改進。它提供了使用同步樣式程式碼非同步存取 resoruces 的方式,而不會阻塞主執行緒。然而,它們也存在一些坑及問題。在本文中,將從不同的角度探討 async/await,並演示如何正確有效地使用這對兄弟。

前置知識

async 作用是什麼

從 MDN 可以看出:

async 函數返回的是一個 Promise 物件。async 函數(包含函數語句、函數表示式、Lambda表示式)會返回一個 Promise 物件,如果在函數中 return 一個直接量,async 會把這個直接量通過 Promise.resolve() 封裝成 Promise 物件。

如果 async 函數沒有返回值, 它會返回 Promise.resolve(undefined)

await 作用是什麼

從 MDN 瞭解到:

await 等待的是一個表示式,這個表示式的計算結果是 Promise 物件或者其它值(換句話說,await 可以等任意表示式的結果)。

如果它等到的不是一個 Promise 物件,那 await 表示式的運算結果就是它等到的東西。

如果它等到的是一個 Promise 物件,await 就忙起來了,它會阻塞後面的程式碼,等著 Promise 物件 resolve,然後得到 resolve 的值,作為 await 表示式的運算結果。

這就是 await 必須用在 async 函數中的原因。async 函數呼叫不會造成阻塞,它內部所有的阻塞都被封裝在一個 Promise 物件中非同步執行。

async/await 的優點

async/await 帶給我們的最重要的好處是同步程式設計風格。讓我們看一個例子:

// async/await
async getBooksByAuthorWithAwait(authorId) {
  const books = await bookModel.fetchAll();
  return books.filter(b => b.authorId === authorId);
}// promise
getBooksByAuthorWithPromise(authorId) {
  return bookModel.fetchAll()
    .then(books => books.filter(b => b.authorId === authorId));
}

很明顯,async/await 版本比 promise 版本更容易理解。如果忽略 await 關鍵字,程式碼看起來就像任何其他同步語言,比如 Python

最佳的地方不僅在於可讀性。async/await 到今天為止,所有主流瀏覽器都完全支援非同步功能。

2.png

本地瀏覽器的支援意味著你不必轉換程式碼。更重要的是,它便於偵錯。當在函數入口點設定斷點並跨過 await 行時,將看到偵錯程式在 bookModel.fetchAll() 執行其任務時暫停片刻,然後它將移動到下一個.filter 行,這比 promise 程式碼要簡單得多,在 promise 中,必須在 .filter 行上設定另一個斷點。

3.gif

另一個不太明顯的優點是 async 關鍵字。 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/waitPromise 進行了比較,並聲稱它是 JavaScript 下一代非同步程式設計風格,對此作者深表異議。async/await 是一種改進,但它只不過是一種語法糖,不會完全改變我們的程式設計風格。

從本質上說,async 函數仍然是 promise。在正確使用 async 函數之前,你必須先了解 promise,更糟糕的是,大多數時候你需要在使用 promises 的同時使用 async 函數。

考慮上面範例中的 getBooksByAuthorWithAwait()getbooksbyauthorwithpromise() 函數。請注意,它們不僅功能相同,而且具有完全相同的介面!

這意味著 getbooksbyauthorwithwait() 將返回一個 promise,所以也可以使用 .then(...)方式來呼叫它。

嗯,這未必是件壞事。只有 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),
  };
}

上述程式碼在邏輯上看似正確的,然而,這是錯誤的。

  1. await bookModel.fetchAll() 會等待 fetchAll() 直到 fetchAll() 返回結果。
  2. 然後 await authorModel.fetch(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),
  };
}

更糟糕的是,如果你想要一個接一個地獲取專案列表,你必須依賴使用 promises:

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中,非同步函數有兩個可能的返回值: resolvedrejected。我們可以用 .then() 處理正常情況,用 .catch() 處理異常情況。然而,使用 async/await方式的,錯誤處理可能比較棘手。

try…catch

最標準的(也是作者推薦的)方法是使用 try...catch 語法。在 await 呼叫時,在呼叫 await 函數時,如果出現非正常狀況就會丟擲異常,await 命令後面的 promise 物件,執行結果可能是 rejected,所以最好把await 命令放在 try...catch 程式碼塊中。如下例子:

class BookModel {
  fetchAll() {
    return new Promise((resolve, reject) => {
      window.setTimeout(() => { reject({'error': 400}) }, 1000);
    });
  }
}// async/await
async getBooksByAuthorWithAwait(authorId) {
try {
  const books = await bookModel.fetchAll();
} catch (error) {
  console.log(error);    // { "error": 400 }
}

在捕捉到異常之後,有幾種方法來處理它:

  • 處理異常,並返回一個正常值。(不在 catch 塊中使用任何 return 語句相當於使用 return undefined,undefined 也是一個正常值。)
  • 如果你想讓呼叫者處理它,你可以直接丟擲普通的錯誤物件,如 throw errorr,它允許你在 promise 鏈中使用 async getBooksByAuthorWithAwait() 函數(也就是說,可以像getBooksByAuthorWithAwait().then(...).catch(error => ...) 處理錯誤); 或者可以用 Error 物件將錯誤封裝起來,如 throw new Error(error),當這個錯誤在控制檯中顯示時,它將給出完整的堆疊跟蹤資訊。
  • 拒絕它,就像 return Promise.reject(error) ,這相當於 throw error,所以不建議這樣做。

使用 try...catch 的好處:

  • 簡單,傳統。只要有Java或c++等其他語言的經驗,理解這一點就不會有任何困難。
  • 如果不需要每步執行錯誤處理,你仍然可以在一個 try ... catch 塊中包裝多個 await 呼叫來處理一個地方的錯誤。

這種方法也有一個缺陷。由於 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 被包含在一系列函數呼叫中,其中一個呼叫者吞噬了錯誤,那麼就很難找到這樣一個未定義的錯誤。

讓函數返回兩個值

另一種錯誤處理方法是受到Go語言的啟發。它允許非同步函數返回錯誤和結果。詳情請看這篇部落格文章:

How to write async await without try-catch blocks in Javascript

簡而言之,你可以像這樣使用非同步函數:

[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 statement
let books = await bookModel.fetchAll()
  .catch((error) => { console.log(error); });

這種方法有兩個小問題:

  • 它是 promises 和 async 函數的混合體。你仍然需要理解 是promises 如何工作的。
  • 錯誤處理先於正常路徑,這是不直觀的。

結論

ES7引入的 async/await 關鍵字無疑是對J avaScrip t非同步程式設計的改進。它可以使程式碼更容易閱讀和偵錯。然而,為了正確地使用它們,必須完全理解 promise,因為 async/await 只不過是 promise 的語法糖,本質上仍然是 promise

英文原文地址:https://hackernoon.com/javascript-async-await-the-good-part-pitfalls-and-how-to-use-9b759ca21cda

更多程式設計相關知識,請存取:!!

以上就是詳解JavaScript中async/await的使用方法的詳細內容,更多請關注TW511.COM其它相關文章!