pending(대기) : 비동기 처리 로직이 아직 완료되지 않은 상태
fulfilled(이행) : 비동기 처리가 완료되어 프로미스가 결과값을 반환해준 상태
내가 원하는 시점을 resolve로 받을 수 있으며 그 시점을 후속처리 메서드 then()을 이용하여 처리결과값을 받을 수 있는 것
rejected(실패) : 비동기 처리가 실패하거나 오류가 발생한 상태
const promise = new Promise((resolve, reject) => {
...
});
.then(첫번째함수(성공), 두번째함수(에러))
resolve (value & then)
reject (error & catch)
promise.then(ouFulfilled);
promise.catch(onRejected);
프로미스 내부에서 resolve가 호출되면 then이 실행되고,
reject가 호출되면 catch가 실행된다.
resolve와 reject에 넣어준 인자는 각각 then과 catch의 매개변수에서 받을 수 있다.
//promise 데이터담기
const a = new Promise((resolve, reject) => {
let data = 'data'
resolve(data)
})
a.then((resolveData) => {
console.log(resolveData)
})
//에러처리
const aErr = new Promise((resolve, reject) => {
setTimeout(() => {
reject('err')
},2000)
});
aErr.then(() => {
console.log('pass')
}).catch((err) => {
console.log(err)
})
const test = new Promise(function(resolve, reject){
setTimeout(() => {
resolve(1);
}, 1000);
})
.then((data1) => {
console.log(data1); // 1
return data1 + 10;
})
.then((data2) => {
console.log(data2); // 11
return data2 + 20;
})
.then((data3) => {
console.log(data3); // 31
});
resolve()가 호출되면 후속메서드 then()을 통해 데이터를 넘겨 받아 실행한다.
1. then()은 resolve()안에 있는 1을 data1로 넘겨받아 실행하고 data1과 10을 더한 후
2. then()으로 넘겨 받아서 같은 로직으로 진행하게 된다