JavaScript에서 비동기 처리가 너무 헷갈립니다. AJAX 요청을 여러 개 순서대로 보내야 하는데, 콜백이 계속 중첩되니까 코드가 엉망이 됩니다.
```javascript
$.ajax({
url: '/api/user',
success: function(user) {
$.ajax({
url: '/api/posts?userId=' + user.id,
success: function(posts) {
$.ajax({
url: '/api/comments?postId=' + posts[0].id,
success: function(comments) {
// 콜백 지옥...
}
});
}
});
}
});
```
이런 콜백 지옥을 해결하는 방법이 있나요?
댓글 4
**1. Promise 체이닝:**
```javascript
fetch('/api/user')
.then(res => res.json())
.then(user => fetch('/api/posts?userId=' + user.id))
.then(res => res.json())
.then(posts => fetch('/api/comments?postId=' + posts[0].id))
.then(res => res.json())
.then(comments => console.log(comments))
.catch(err => console.error(err));
```
**2. async/await (ES2017, 가장 추천):**
```javascript
async function getData() {
try {
const user = await fetch('/api/user').then(r => r.json());
const posts = await fetch('/api/posts?userId=' + user.id).then(r => r.json());
const comments = await fetch('/api/comments?postId=' + posts[0].id).then(r => r.json());
console.log(comments);
} catch(err) {
console.error(err);
}
}
```
async/await가 가장 읽기 쉽고 직관적입니다. Babel을 쓰면 구형 브라우저에서도 사용 가능합니다.
```javascript
$.ajax({url: '/api/user'}).then(function(user) {
return $.ajax({url: '/api/posts?userId=' + user.id});
}).then(function(posts) {
// ...
});
```
```javascript
const [user, config] = await Promise.all([
fetch('/api/user').then(r => r.json()),
fetch('/api/config').then(r => r.json())
]);
```