返回課程

使用 async/await 重寫

使用 async/await 取代 .then/catch,重寫章節 Promise 串接 中的範例程式碼

function loadJson(url) {
  return fetch(url)
    .then(response => {
      if (response.status == 200) {
        return response.json();
      } else {
        throw new Error(response.status);
      }
    });
}

loadJson('https://javascriptinfo.dev.org.tw/no-such-user.json')
  .catch(alert); // Error: 404

註解在程式碼下方

async function loadJson(url) { // (1)
  let response = await fetch(url); // (2)

  if (response.status == 200) {
    let json = await response.json(); // (3)
    return json;
  }

  throw new Error(response.status);
}

loadJson('https://javascriptinfo.dev.org.tw/no-such-user.json')
  .catch(alert); // Error: 404 (4)

註解

  1. 函式 loadJson 變成 async

  2. 所有內部的 .then 都以 await 取代。

  3. 我們可以 return response.json(),而不必等待它,如下所示

    if (response.status == 200) {
      return response.json(); // (3)
    }

    然後外部程式碼必須await該承諾才能解決。在我們的案例中,這並不重要。

  4. loadJson拋出的錯誤由.catch處理。我們無法在那裡使用await loadJson(…),因為我們不在async函數中。