게으른개발너D

Async/ Await - async await, try catch finally, parallel async await 본문

개발/JavaScript

Async/ Await - async await, try catch finally, parallel async await

lazyhysong 2023. 3. 30. 21:04

✨ Async Await ✨

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/async_function

 

async function - JavaScript | MDN

async function 선언은 AsyncFunction객체를 반환하는 하나의 비동기 함수를 정의합니다. 비동기 함수는 이벤트 루프를 통해 비동기적으로 작동하는 함수로, 암시적으로 Promise를 사용하여 결과를 반환

developer.mozilla.org

async, await는 두 Promise의 업데이트이다.

async, await를 만든 이유는 보기 좋은 코드를 만들기 위해서이다.

then이나 catch같은 것들은 구식이다.

많은 then을 사용해야 하는 문제가 있기 때문이다.

 

async, await는 기본적으로 Promise 밖에서 값을 가져올 수 있는 방법이다.

많은 then이나 catch를 사용하지 않고 말이다.

 


먼저 await는 혼자서 사용할 수 없다.

await는 async function 안에서만 사용할 수 있다.

async function은 이렇게 만들 수 있다.

const getMovies = async () => {};

async function getMovies() {};

이제 우리가 할 일은 Promise를 끝내기 위해 많은 then을 사용하는 대신 await를 사용하면 된다.

 

 

const getMoviesPromise = () => {
  fetch("https://yts.mx/api/v2/list_movies.json")
    .then(response => {
      console.log(response);
      return response.json();
    })
    .then(json => console.log(json))
    .catch(error => console.log(`X ${error}`));
}

const getMoviesAsync = async () => {
  const response = fetch("https://yts.mx/api/v2/list_movies.json");
  console.log(response);
};

getMoviesAsync();

Promise와 Async를 비교하기위해 이렇게 적어보자

 

const getMoviesAsync = async () => {
  const response = await fetch("https://yts.mx/api/v2/list_movies.json");
  console.log(response);
};

async 함수 안에 await를 추가해주었다.

 

await는 Promise가 끝나기를 기다린다.

그리고 response를 Promise에서 했던 것처럼 response 변수에 넣어준다.

기본적으로 resolve 된 값을 response 변수에 넣어주는 것이다.

 

await fetch에서 resolve 된 값은 같은 response지만 response 변수에 들어올 것이다.

await만 썼는데 Promise에서 .then(response => response) 했는 결과와 같은 값을 가져오고 있다.

const getMoviesPromise = () => {
  fetch("https://yts.mx/api/v2/list_movies.json")
    .then(response => {
      console.log(response);
      return response.json();
    })
    .then(json => console.log(json))
    .catch(error => console.log(`X ${error}`));
}

const getMoviesAsync = async () => {
  const response = await fetch("https://yts.mx/api/v2/list_movies.json");
  const json = await response.json();
  console.log(json);
};

getMoviesAsync();

 

response.json() 도 이렇게 얻을 수 있다.

 

await는 promise가 끝나길 기다려주는 것이다.

resolve 되든 reject 되든 상관없다.

 

 

✨ Try Catch Finally ✨

 

이제 우리는 async await 를 이용하여 then, then, then을 피하는 방법을 안다!

이제 catch를 써보자!

 

try, catch를 써볼 것인데, 다른 언어에선 이미 있었지만 JS에선 새롭게 추가된 기능이다.

 

catch랑 then 대신 우리가 해볼 것은, 우리는 뭔가를 try 해볼 것이다.

그리고 이게 작동하지 않으면 error를 catch 해볼 것이다.

const getMoviesAsync = async () => {
  try {
    const response = await fetch("https://yts.mx/api/v2/list_movies.json");
    const json = await response.json();
    console.log(json);
  } catch (error) {
    console.log(error);
  }
};

console.log를 이용해서 JSON 데이터를 찍을 건데, 이게 동작을 안하면 console.log로 error를 찍어볼 것이다.

성공하면 이렇게,

실패하면 이렇게 찍힐 것이다.

 

 

catch는 async await에서 일어나는 모든 error를 잡는다.

 


finally 같은 건 async await 에 없을까?

당연히 있다!!

그냥 마지막에 finally만 추가해 주면 된다.

const getMoviesAsync = async () => {
  try {
    const response = await fetch("https://yts.mx/api/v2/listmovies.json");
    const json = await response.json();
    console.log(json);
  } catch (error) {
    console.log(error);
  } finally {
    console.log("We are done!");
  }
};

이렇게 에러가 찍히지만 마지막 finally의 We are done도 마지막에 찍힌다!

 


try 안에서 error를 발생시키면 어떻게 될까?

const getMoviesAsync = async () => {
  try {
    const response = await fetch("https://yts.mx/api/v2/list_movies.json");
    const json = await response.json();
    console.log(json);
    throw Error("I'm hungry/");
  } catch (error) {
    console.log(error);
  } finally {
    console.log("We are done!");
  }
};

 

던진 error가 찍힌다.

catch block이 await 안에 있는 error만 잡는게 아니라, 밖에 있는 error까지 잡는다.

어떤 에러가 try 블록에 있든지 무조건 잡는다.

 


https://dev.to/gafi/7-reasons-to-always-use-async-await-over-plain-promises-tutorial-4ej9

 

7 Reasons Why JavaScript Async/Await Is Better Than Plain Promises (Tutorial)

Async/await was introduced in NodeJS 7.6 and is currently supported in all modern browsers. I believe...

dev.to

 

async await 가 왜 좋은지에 대한 설명이다.

읽어보도록!!

 

 

✨ Parallel Async Await ✨

 

비동기(Async) Parallel에 대해 알아보자

 

우리가 두 개의 API를 얻는다고 하자.

const getMoviesAsync = async () => {
  try {
    const response = await fetch("https://yts.mx/api/v2/list_movies.json");
    const json = await response.json();
    console.log(json);
  } catch (error) {
    console.log(error);
  } finally {
    console.log("We are done!");
  }
};

getMoviesAsync();

const getUpcomingMoviesAsync = async () => {
  try {
    const response = await fetch("https://yts.am/api/v2/list_suggestions.json");
    const json = await response.json();
    console.log(json);
  } catch (error) {
    console.log(error);
  } finally {
    console.log("We are done!");
  }
};

getUpcomingMoviesAsync();

이걸 위해 Promise.all을 쓸 것이고, destructuring assignment(구조 분해 할당)을 할 것이다.

const getMoviesAsync = async () => {
  try {
    const response = await Promise.all([
      fetch("https://yts.mx/api/v2/list_movies.json"), 
      fetch("https://yts.am/api/v2/list_suggestions.json")
    ]);
    const json = await response.json();
    console.log(json);
  } catch (error) {
    console.log(error);
  } finally {
    console.log("We are done!");
  }
};

일단 Promise.all을 썼는데, 알다시피 뒤에 then을 붙여서 얻은 결과의 value 값은 promise 결과값의 array이다.

 

우리가 response 결과물을 얻는 대신 할 수 있는 건, destructuring을 사용하는 것이다.

우리가 첫번째 취할 value는 movies, 두번째 value는 upcoming이다,

const getMoviesAsync = async () => {
  try {
    const [movies, upcoming] = await Promise.all([
      fetch("https://yts.mx/api/v2/list_movies.json"), 
      fetch("https://yts.am/api/v2/list_suggestions.json")
    ]);
    const json = await response.json();
    console.log(json);
  } catch (error) {
    console.log(error);
  } finally {
    console.log("We are done!");
  }
};

response.json 값을 얻기 위해 이렇게 고쳐 써보자.

const getMoviesAsync = async () => {
  try {
    const [moviesResponse, upcomingResponse] = await Promise.all([
      fetch("https://yts.am/api/v2/list_movies.json"), 
      fetch("https://yts.am/api/v2/list_suggestions.json")
    ]);
    const [movies, upcoming] = await Promise.all([
      moviesResponse.json(),
      upcomingResponse.json()
    ]);
    console.log(movies, upcoming);
  } catch (error) {
    console.log(error);
  } finally {
    console.log("We are done!");
  }
};

getMoviesAsync();

 

 

 

 

axios라는 것이 있는데, 우릴 위해서 저 저저 중간 단계들을 대신 해주고 있다

이것도 공부해 보자!

Comments