# 【ES6】async / await

### 使用方式

```JavaScript
// #1 當資料有順序性的時候
const fn1 = () =>{
  axios.get("https://randomuser.me/api/")
  .then((res)=> {
    console.log("fn1 seed",res.data.info.seed);
    const seed = res.data.info.seed;
    return axios.get(`https://randomuser.me/api/?seed=${seed}`)
  })
  .then((res)=>{
    console.log("fn1 seed2",res.data.info.seed)
  })
}

// #2 使用 async await 來修改
const fn2 = async ()=> {
  const res = await axios.get("https://randomuser.me/api/")
  const seed = res.data.info.seed;
  console.log("fn2 seed",res.data.info.seed);
  const res2 = await axios.get(`https://randomuser.me/api/?seed=${seed}`);
  const seed2 = res2.data.info.seed;
  console.log("fn2 seed2",res2.data.info.seed);
}


// #3 立即函式的寫法
(async function(){
  const res = await axios.get("https://randomuser.me/api/")
  const seed = res.data.info.seed;
  console.log("fn3 seed",res.data.info.seed);
  const res2 = await axios.get(`https://randomuser.me/api/?seed=${seed}`);
  const seed2 = res2.data.info.seed;
  console.log("fn3 seed2",res2.data.info.seed);
})();


```

### 錯誤處理

```JavaScript
const fn4 = async () => {
  try {
    const res = await axios.get("https://randomuser.me/api/")
    return res
  } catch (error) {
    throw error
  }
}

fn4()
.then((res)=>{
  console.log(res);
})
.catch((err)=>{
  console.log(err);
});
```

### async function 本身就是 promise

[![image-1674748127619.png](https://bookstack.treemanou.com/uploads/images/gallery/2023-01/scaled-1680-/MPzDB9hd4GsVTixg-image-1674748127619.png)](https://bookstack.treemanou.com/uploads/images/gallery/2023-01/MPzDB9hd4GsVTixg-image-1674748127619.png)

### async Function 與 React

```JavaScript

// async Function 與 React
const App = () => {
  const [data, setData] = React.useState({}) 

  React.useEffect(() => {
    (async () => {
      const res = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
      console.log(res);
      setData(res.data);
    })();
  }, []);

  return <div>
    {data.title}
  </div>
}

```