[ES6] Async/Await

Cho Dragoo·2021년 9월 5일
0

ES6 문법

목록 보기
3/3

'노마드코더의 ES6의 정석' 동영상 강의를 토대로 복습한 내용입니다.

Async/Await는 Promises를 좀 더 좋게 바꿔주는 문법이다.

Promises 영향권 밖에서 then(),catch()을 쓰지 않고 좀 더 읽기 좋은 코드로 만들 수 있다.



Async/Await 기본사용법

const getFoxPhoto = () => {
  fetch("https://randomfox.ca/floof/")
    .then((response) => {
      console.log(response.type);
      return response;
    })
    .then((response) => {
      console.log(response.url);
      return response;
    })
    .then((response) => {
      console.log(response.status);
      return response;
    })
    .catch((e) => console.log(`${e}`));
};

getFoxPhoto();

// cors
// https://randomfox.ca/floof/
// 200
  • 기존의 Promises 문법에서는 로직을 추가할때마다 then()함수를 계속 붙여줘야 한다.이는 점차 가독성을 해치게 되는 부작용이 일어난다.

const getFoxPhoto = async () => {
  const response = await fetch("https://randomfox.ca/floof/");
  console.log(response.type);
  console.log(response.url);
  console.log(response.status);
};

getFoxPhoto();

// cors
// https://randomfox.ca/floof/
// 200
  • 이를 해결하기 위해 ES6에서 추가된 Async/Await 문법을 더하면 then()없이 변수의 대입 만으로 데이터를 간단하게 다룰 수 있다.
  • 적용법은 모든 내용이 담긴 함수에 async를 붙이고 비동기적으로 받을 데이터가 있는 함수에는 await를 붙인다. 예제대로면 awaitfetch함수 앞에 붙이는 것이다
  • return문도 필요 없으니 코드의 가독성도 좋아진다.



try/catch 추가

const getFoxPhoto = async () => {
  try {
    const response = await fetch("https://randomfox.ca/floof/");
    console.log(response.type);
    console.log(response.url);
    console.log(response.status);
  } catch (error) {
    (error) => console.log(`${error}`);
  }
};

getFoxPhoto();
  • Async/Await문법에서 에러를 잡기위해 catch()를 쓰고 싶다면 try/catch문법을 쓰자.
  • 기존의 내용은 try 객체로 옮기고 에러가 나올 때 작동할 로직은 catch 객체로 정착하면 된다.
profile
어떤 문제든 파악 할 수 있으며 해결책을 찾을 수 있는 개발능력을 꿈꾸고 있습니다.

0개의 댓글