---
# System prepended metadata

title: "\U0001F3C5 Day 3 - async await"
tags: [Node.js 直播班 - 2024 春季班]

---

# 🏅 Day 3 - async、await
async 及 await 是執行非同步函式的一種寫法，此寫法可以讓非同步函式在閱讀上更接近同步函式

在非同步函式前加上 `async` 關鍵字，執行此函式時回傳值就會被轉為一個 Promise 
在 `async` 內，使用 `await` 接收回傳的結果，`await` 會暫停此 `async` 函式的執行，並且等待 `await` 後方函式回傳結果後再繼續執行 `async` 函式（也就是說在未等待到結果回傳前，不會執行 `await` 下面程式碼）。
另外 `async`、`await` 通常會搭配 `try...catch` 來進行錯誤處理。

改寫前一天 `帶入參數` 的範例如下：
```javascript=
const checkRoomRating = rating => {
  return new Promise((resolve, reject) => {
    if (rating >= 3) {
      resolve(rating);  
    } else {
      reject('未達評分標準');
    }
  });
};

// 改為使用 async await 
const getData = async (rating) => {
  try {
    const data = await checkRoomRating(rating); // 等待回傳結果後再接續執行下方程式碼
    console.log(data);  // 印出 data 的值
  } catch (error) {
    // 接收 reject 傳遞的資料
    console.log(error); // 印出 '未達評分標準' 
  }
}

getData(4);  // 4
getData(2);  // '未達評分標準' 
```


### 參考資源
- [Async function / Await 深度介紹 | 卡斯伯 Blog - 前端，沒有極限](https://www.casper.tw/development/2020/10/16/async-await/)
- [async and await | MDN](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises#async_and_await)
- 課程影音「async、await 再升級」

題目
---
延續前一天題目解答，將 Promise `.then .catch` 鏈式寫法（下方註解區塊）改為使用 `async await` 搭配 `try...catch` 寫法 

```javascript=
const historyOrdersData = [{
  room: '豪華雙人房',
  price: 3200,
  user: 'Tom'
},{
  room: '高級雙人房',
  price: 2800,
  user: 'Tom'
},{
  room: '高級雙人房',
  price: 2800,
  user: 'Tommy'
}];

const getUserData = (name) => {
  return new Promise((resolve, reject) => {
    const data = {
      user: name,
      orderSum: 0,
      orderTimes: 0,
    };
    historyOrdersData.forEach((item) => {
      if (item.user === name) {
        data.orderSum += item.price;
        data.orderTimes += 1;
      }
    });
    if (data.orderTimes) {
      resolve(data);
    } else {
      reject('該使用者無訂房紀錄');
    }
  })
};

const checkVip = (data) => {
  return new Promise((resolve, reject) => {
    if (data.orderSum >= 10000) {
      resolve(`累計訂房金額： ${data.orderSum} 元，已達升級 VIP 會員資格`);
    } else {
      const price = 10000 - data.orderSum;
      reject(`還差 ${price} 元，才可升級 VIP 會員`);
    }
  });
};

/** 將此區塊改寫至下方程式碼（調整 ... 部分）
getUserData('Tom')
  .then(data => checkVip(data))
  .then(isVipStr => console.log(isVipStr))
  .catch(error => console.log(error))
*/

// 使用 async await
const init = ... () => {
  try {
    const data = ... ...('Tom');
    const isVipStr = ... ...(data);
    console.log(...);
  } catch (error) {
    console.log(error);
  }
};

init();
```


## 回報流程

將答案寫在 CodePen 並複製 CodePen 連結貼至底下回報就算完成了喔! 
解答位置請參考下圖（需打開程式碼的部分觀看）

![](https://i.imgur.com/vftL5i0.png)

<!-- 解答：  
```javascript=
const historyOrdersData = [{
  room: '豪華雙人房',
  price: 3200,
  isCoupon: true,
  user: 'Tom'
},{
  room: '高級雙人房',
  price: 2800,
  isCoupon: true,
  user: 'Tom'
},{
  room: '高級雙人房',
  price: 2800,
  isCoupon: true,
  user: 'Tommy'
}];

const getUserData = (name) => {
  return new Promise((resolve, reject) => {
    const data = {
      user: name,
      orderSum: 0,
      orderTimes: 0,
    };
    historyOrdersData.forEach((item) => {
      if (item.user === name) {
        data.orderSum += item.price;
        data.orderTimes += 1;
      }
    });
    if (data.orderTimes) {
      resolve(data);
    } else {
      reject('該使用者無訂房紀錄');
    }
  })
};

const checkVip = (data) => {
  return new Promise((resolve, reject) => {
    if (data.orderSum >= 10000) {
      resolve(`累計訂房金額： ${data.orderSum} 元，已達升級 VIP 會員資格`);
    } else {
      const price = 10000 - data.orderSum;
      reject(`還差 ${price} 元，才可升級 VIP 會員`);
    }
  });
};


const init = async () => {
  try {
    const data = await getUserData('Tom');
    const isVipStr = await checkVip(data);
    console.log(isVipStr);
  } catch (error) {
    console.log(error);
  }
};
init();
```
-->




回報區
---
<!-- 
將答案貼至下方表格內，格式：
| Discord 暱稱 | [CodePen](連結) |
-->

|    Discord    |   CodePen ／ 答案  |
|:-------------:|:-----------------:|
| xxx | [CodePen]() |
| 2魚. | [CodePen](https://codepen.io/ijrekmsn-the-sans/pen/LYvOWrW) |
| Lobinda | [CodePen](https://codepen.io/Lobinda/pen/XWQzGVP) |
| 群嘉 | [CodePen](https://codepen.io/efzdamnp-the-lessful/pen/OJGvxGa?editors=0012)|
| shuantt | [CodePen](https://codepen.io/th-tseng/pen/BaErwEv)|
| ellallu0903 | [CodePen](https://codepen.io/ellallu0903/pen/KKYoyMp)|
| YC | [CodePen](https://codepen.io/YCLu/pen/XWQEzKp)|
| 羽 | [CodePen](https://codepen.io/lingling-Syu/pen/qBwoVLM?editors=0011)|
| RayRay | [CodePen](https://codepen.io/CityRay/pen/mdgxqYN)|
| Otis | [CodePen](https://codepen.io/humming74/pen/KKYoZmy?editors=0012)|
| Jean | [CodePen](https://codepen.io/jeanchiang1221/pen/oNOqpVX)|
| Ingridkao | [CodePen](https://codepen.io/ingrid_kao/pen/XWQEVKY?editors=0010)|
| kelvinnn | [CodePen](https://codepen.io/is-lin/pen/zYXWpbX?editors=0011)|
| Tiya | [CodePen](https://codepen.io/Tiya_blank/pen/YzMeQwR)|
| Chia Pin | [CodePen](https://codepen.io/joker-cat/pen/bGJvLRj)|
|cho|[CodePen](https://codepen.io/cho195/pen/xxeWYXV)|
|Aida|[CodePen](https://codepen.io/ada23410/pen/jORzzpr?editors=0011)|
|Render Lai| [CodePen](https://codepen.io/hsinhui/pen/KKYoRPW)|
|瑀君|[CodePen](https://codepen.io/yennnnn/pen/jORzKwX)|
|william_hsu|[CodePen](https://codepen.io/william8815/pen/rNbdrJm)|
|wei|[CodePen](https://codepen.io/Wei-the-sasster/pen/LYvdBrr?editors=0012)|
|ej_chuang|[CodePen](https://codepen.io/EJChuang/pen/WNWzKYr)|
|yiling4054|[CodePen](https://codepen.io/lin010/pen/BaErOyj?editors=0011)|
| zaoannihao | [CodePen](https://codepen.io/ckhwdvrx-the-solid/pen/dyLmqPr) |
| Alan | [CodePen](https://codepen.io/l0f0/pen/zYXWJra?editors=0011) |
| Theodore | [CodePen](https://codepen.io/GustavoFringgg/pen/VwNXErp?editors=1011) |
| tung030374 | [CodePen](https://codepen.io/tung__u/pen/vYMRvjO?editors=0011) |
| YJ | [CodePen](https://codepen.io/y0000ga/pen/rNbdPoV) | 
| 阿旭 | [CodePen](https://codepen.io/1997-work/pen/NWmYQmw?editors=1111) | 
| 苡安 | [CodePen](https://codepen.io/yi-an-yang/pen/JjVvjOO?editors=0012) | 
| Ciel | [CodePen](https://codepen.io/nycteachen/pen/GRLdqrY) | 
| blp100x | [CodePen](https://codepen.io/blp100/pen/MWRGpZX) | 
| Tippy | [CodePen](https://codepen.io/Ektodor-Wang/pen/NWmMXZv) | 
| 圈圈 | [CodePen](https://codepen.io/wjejfczn-the-bold/pen/vYMjaMQ) |
| Hank | [CodePen](https://codepen.io/tw1720/pen/QWPrzrv) |
| Fabio20 | [CodePen]([連結](https://codepen.io/fabio7621/pen/PogawEq?editors=0011)) |
| runweiting | [CodePen](https://codepen.io/weiting14/pen/bGJKjrO) |
| Thomas | [CodePen](https://codepen.io/ThomasYeh/pen/RwOJqyM) |
| Johlmike | [CodePen](https://codepen.io/johlmike/pen/QWPxzPp) |
| Sophiee | [CodePen](https://codepen.io/sophiee2727/pen/xxezBBr) |
| william 威良 | [CodePen](https://codepen.io/snowman12320/pen/KKYBKxO?editors=1011) |
| Mei | [Codepen](https://codepen.io/l_umei/pen/NWmBjXv) |
| Esther | [Codepen](https://codepen.io/xueefddg-the-sans/pen/poBZLEq) |
| jenny7532 | [Codepen](https://codepen.io/wei-chen-wu/pen/LYvBJWQ?editors=1112) |
| Henry | [Codepen](https://codepen.io/hekman1122/pen/RwOBzLg?editors=0012) |
| yoshidc | [CodePen](https://codepen.io/yoshiyyc/pen/PogBMKL) |
| Benson | [CodePen](https://codepen.io/nosneb83/pen/wvZEgop) |
| aprilccc | [CodePen](https://codepen.io/vocalise_com/pen/oNOPeQy) |
| jules | [CodePen](https://codepen.io/cjntfsoq-the-animator/pen/yLrxpGa?editors=1111) |
| Ching | [CodePen](https://codepen.io/huangching/pen/BaEvZxL) |
| albertyang3576 | [CodePen](https://codepen.io/albertyang3576/pen/NWmJdKZ) |
| 柚子 | [CodePen](https://codepen.io/as6625998/pen/NWVPWXj?editors=1011) |
| 郭芙蘭 | [CodePen](https://codepen.io/flora_Kuo/pen/VwOYOxx?editors=0011) |
| puffy_chen| [CodePen](https://codepen.io/TernMayDay/pen/jOobeKR?editors=0001)
| SKey | [CodePen](https://codepen.io/Dale-Chien/pen/ExBdWrV)