resolve, reject 콜백으로 프로미스 결과 반환.then()을 통해 순차적으로 작업을 이어갈 수 있음new Promise((resolve, reject) => {
resolve("성공 메시지");
})
.then(msg => msg + " 추가 메시지")
.then(finalMsg => console.log(finalMsg));
XMLHttpRequest를 Promise로 감싸 비동기 로직을 단순화.then()을 통해 중첩 요청을 순차적으로 처리function fetchGet(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.send();
xhr.onload = () => resolve(JSON.parse(xhr.responseText));
xhr.onerror = () => reject("에러 발생");
});
}
fetchGet('/users')
.then(users => fetchGet(`/posts?userId=${users[1].id}`))
.then(posts => fetchGet(`/comments?postId=${posts[3].id}`))
.then(comments => renderComments(comments));
.post DOM으로 동적 생성.then(posts => displayPosts(posts.slice(0, 5)))
.catch(error => showError(error))
.finally(() => console.log("완료"));
fetch(url).then().catch()로 사용 가능async function 내에서 await로 코드 간결화async function fetchData() {
const res = await fetch(url);
const data = await res.json();
console.log(data);
}
Content-Type: application/jsonoffset, limit 사용해 페이지네이션 구현const res = await fetch(`${pokeUrl}?offset=${offset}&limit=${limit}`);
const { results } = await res.json();
offset 이동✅ 총정리