4. Promise 활용 비동기 처리
Promise 생성자 함수는 자신의 인수로 비동기 처리를 수행할 콜백 함수를 받음
→ ECMAScript에서는 이 콜백 함수를 executor function이라고 부름
sample.js
const executor = () => {};
const myPromise = new Promise(executor);이 콜백 함수 안에서 비동기 처리를 수행할 코드를 작성할 수 있음
sample.js
const executor = () => {
const xhr = new XMLHttpRequest();
const url = 'https://jsonplaceholder.typicode.com/posts/1';
xhr.open('GET', url);
xhr.onload = () => {
if (xhr.status === 200) {
// 응답 성공
console.log(JSON.parse(xhr.response)); // JSON 데이터 { ... }
} else {
// 에러 처리
console.log(xhr.status);
}
}
xhr.send();
};
const promise = new Promise(executor);
console.log(promise); // pending1. resolve와 reject 콜백
Promise 생성자의 인수로 전달한 콜백 함수 executor는
비동기 처리 결과에 따른 후속 처리를 수행하기 위해 두 개의 콜백 함수를 자신의 인수로 전달받아 동작함
| 함수 | 역할 | 호출 결과 상태 |
|---|---|---|
| resolve | 비동기 작업이 성공했을 때 호출됨 | fulfilled |
| reject | 비동기 작업이 실패했을 때 호출됨 | rejected |
비동기 작업이 성공적으로 완료되었을 경우 resolve를, 실패하였을 경우 경우 reject 함수를 호출할 수 있음
다음과 같이 resolve, reject 함수의 인수에 처리 결과값을 작성하면 됨
2-1. resolve 콜백
fulfilled.js
const executor = (resolve, reject) => {
resolve('처리 성공');
};
const promise = new Promise(executor);
console.log(promise);
/*
5번 Line. 출력 결과
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: "처리 성공"
*/2-2. reject 콜백
rejected.js
const executor = (resolve, reject) => {
reject('처리 실패');
};
const promise = new Promise(executor);
console.log(promise);
/*
5번 Line. 출력 결과
[[Prototype]]: Promise
[[PromiseState]]: "rejected"
[[PromiseResult]]: "처리 실패"
*/2-3. XHR에 resolve와 reject를 추가한 코드 예시
sample.js
const executor = (resolve, reject) => {
const xhr = new XMLHttpRequest();
const url = 'https://jsonplaceholder.typicode.com/posts/1';
xhr.open('GET', url);
xhr.send();
xhr.onload = () => {
if (xhr.status === 200) {
// 응답 성공
const data = JSON.parse(xhr.response);
resolve(data);
} else {
// 에러 처리
console.log(xhr.status);
reject('실패');
}
}
};Last updated on