iT邦幫忙

0

【30 天JavaScript 實戰 】 Day 19|async/await

2025-12-04 02:52:25150 瀏覽
  • 分享至 

  • xImage
  •  

有時候我們只是想抓個資料,為什麼 then 一層又一層?
所以今天我們要來把 Promise 變成更直覺、更乾淨的寫法!

今日的目標:

  • 了解async/await

1. 什麼是 async/await?

async/await 是 Promise 的語法糖,可以把非同步寫得像一般同步流程一樣順~
看起來像這樣:

async function getUser() {
  const res = await fetch("/api/user");
  const data = await res.json();
  console.log(data);
}

**2. async 搭配 await **

只要你在函式前面加上 async,這個函式就會自動回傳 Promise
而await是讓程式暫停,等 Promise 回來,再繼續往下走。

用 .then().then().catch() 的寫法(Promise 版本)

fetch("/api/user")
  .then(res => {
    if (!res.ok) {
      throw new Error("API 回傳錯誤:" + res.status);
    }
    return res.json();   // 這裡還是回傳 Promise
  })
  .then(data => {
    console.log("使用者資料:", data);
  })
  .catch(err => {
    console.error("發生錯誤:", err);
  });

async/await 寫法

async function getUser() {
  try {
    const res = await fetch("/api/user");
    
    if (!res.ok) {
      throw new Error("API 回傳錯誤:" + res.status);
    }

    const data = await res.json();
    console.log("使用者資料:", data);

  } catch (err) {
    console.error("發生錯誤:", err);
  }
}

getUser();

3. 常見情境:GET API

async function getUser() {
  const res = await fetch("/api/user");
  const data = await res.json();
  return data; // 有 return!要把資料「回傳」給外面用,外面必須 .then 或 await
}

getUser().then(user => console.log(user));

為什麼最後面還是用 .then()?
因為 async function 回傳 Promise,外面要拿結果依然要用 .then 或 await。

4. async/await 的錯誤處理:try/catch

比起 .catch(),async/await 的錯誤處理更清楚:

async function getUser() {
  try {
    const res = await fetch("/api/user");
    if (!res.ok) throw new Error("API 回傳錯誤狀態碼");

    const data = await res.json();
    return data;

  } catch (err) {
    console.error("出錯了:", err);
  }
}

為什麼 fetch 不能只有 .catch()?
因為 fetch 不會因為 400/500 而丟錯,它只會在網路失敗時才 catch
所以 if (!res.ok) 是必要的。


/images/emoticon/emoticon08.gif


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言