async/await랑 Promise.then() 중 뭘 써야 하나요? 차이가 뭔가요?
둘 다 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()을 활용하면 됩니다.
Promise.all()
댓글 1
둘 다 Promise를 다루는 방법이지만 async/await가 코드 가독성이 훨씬 좋습니다.
async/await를 기본으로 쓰세요. 병렬 처리가 필요하면
Promise.all()을 활용하면 됩니다.