프로미스를 사용해서 비동기 프로그래밍을 하다보면 콜백 헬에 빠지게 된다
이때 async와 await를 사용하는 이유는 기존의 비동기 처리 방식인 콜백 함수와 프로미스의 단점을 보완하고 가독성을 높여주기 때문이다
async function 함수명() {
await 비동기_처리_메서드_명();
}
function pickFruits() {
return getApple().then(apple => {
return getBanana().then(banana => `${apple} + ${banana}`)
});
}
위의 코드는 Promise가 여러개가 중첩되면서 가독성이 떨어지는 문제가 있다.
// async & await 🤔
async function pickFruits() {
const apple = await getApple();
const banana = await getBanana();
return `${apple} + ${banana}`;
}
await를 이용해서 Promise를 직렬적으로 처리한다.
그러나 비효율적이라는 문제가 있다.
promise API를 이용 → Promise.all 한번에 병렬적으로 처리가 가능 😃
function getUserData() {
fetch(`https://api.github.com/users`)
.then(res => res.json())
.catch(err => console.log(err))
}
// 위의 코드를 async await를 이용하면
async function getUserData() {
const res = await fetch(`https://api.github.com/users`);
const data = await res.json();
}
또다른 예제를 보도록 하자
// fetch user data
function fetchUser() {
var url = `https://api.github.com/users`;
return fetch(url).then(res => res.json());
}
// fetch todo data
function fetchTodo() {
var url = `https://jsonplaceholder.typicode.com/todos`;
return fetch(url).then(res => res.json());
}
async function logTodoTitle() {
var user = await fetchUser();
if (user[0].id === 1) {
var todo = await fetchTodo();
console.log(todo[0].title);
}
}
logTodoTitle();
promise를 이용한 콜백함수를 만든 것보다 더 가독성이 좋고 비동기 처리 방식으로 사고하지 않아도 된다는 장점이 있다
https://joshua1988.github.io/web-development/javascript/js-async-await/