'노마드코더의 ES6의 정석' 동영상 강의를 토대로 복습한 내용입니다.
Async/Await는 Promises를 좀 더 좋게 바꿔주는 문법이다.
Promises 영향권 밖에서 then(),catch()을 쓰지 않고 좀 더 읽기 좋은 코드로 만들 수 있다.
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
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
then()
없이 변수의 대입 만으로 데이터를 간단하게 다룰 수 있다.async
를 붙이고 비동기적으로 받을 데이터가 있는 함수에는 await
를 붙인다. 예제대로면 await
를 fetch
함수 앞에 붙이는 것이다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
객체로 정착하면 된다.