본문 바로가기
Q&A2022년 1월 1일1분 읽기

JavaScript 비동기 처리 async/await 질문

오
오수빈
조회 764댓글 1

async/await랑 Promise.then() 중 뭘 써야 하나요? 차이가 뭔가요?

댓글 1

김김영삼4년 전

둘 다 Promise를 다루는 방법이지만 async/await가 코드 가독성이 훨씬 좋습니다.

// Promise.then()
fetch("/api/users")
.then(res => res.json())
.then(data => {
return fetch(`/api/users/${data[0].id}/posts`);
})
.then(res => res.json())
.then(posts => console.log(posts))
.catch(err => console.error(err));

// async/await (같은 로직)
async function getPosts() {
try {
const res = await fetch("/api/users");
const data = await res.json();
const postsRes = await fetch(`/api/users/${data[0].id}/posts`);
const posts = await postsRes.json();
console.log(posts);
} catch (err) {
console.error(err);
}
}

async/await를 기본으로 쓰세요. 병렬 처리가 필요하면 Promise.all()을 활용하면 됩니다.

Ctrl+Enter로 등록