// 콜백 함수의 중첩 사용
function requestData1(callback) {
// ...
callback(data);
}
function requestData2(callback) {
// ...
callback(data)
}
function onSuccess1(data) {
console.log(data);
requestData2(onSuccess2);
}
function onSuccess2(data) {
console.log(data);
}
requestData1(onSuccess1);
// 프로미스 코드
requestData1()
.then(data => {
console.log(data);
return requestData2();
})
.then(data => {
console.log(data);
});
const promise1 = new Promise((resolve, reject) => {
// ...
// resolve(data)
// or reject('error message')
})
const promise2 = Promise.resolve(data);
const promise3 = Promise.reject('error message');
then
then 은 fullfilled 상태의 프로미스를 처리할 때 주로 사용되는 메소드다.
프로미스가 fullfilled 상태가 되면 then 메소드의 첫번째 인수로 전달된 함수가 호출된다
프로미스가 rejected 상태가 되면 then 메소드의 두번째 인수로 전달된 함수가 호출된다
requestData().then(onResolve, onReject);
// fullfilled 상태가 되면 onResolve 함수가 호출되고
// rejected 상태가 되면 onReject 호출
then 메소드는 항상 프로미스를 반환한다
then 에서 프로미스를 반환하면 프로미스 객체 그대로 반환하고
프로미스가 아닌 값을 반환하면 그 값을 resolve하는 프로미스를 반환한다
함수 내부에서 예외가 발생하면 rejected 상태의 프로미스를 반환한다
따라서 하나의 프로미스로부터 연속적으로 then 메소드를 호출할 수 있다
// 연속해서 then 호출하기
requestData1()
.then(data => {
return requestData2();
})
.then(data => {
return data + 1;
})
.then(null, error => {
console.log(error);
});
Promise.reject('ERROR')
.then(() => console.log(1))
.then(() => console.log(2))
.then(() => console.log(3), () => console.log(4))
.then(() => console.log(5), () => console.log(6))
// 무엇이 출력될까? 4,5가 출력된다
catch
Promise.resolve().then(
() => {
throw new Error('error');
},
error => {
console.log(error); // 같은 then 안의 onResolve의 에러는 onReject에서 처리할 수 없다
}
);
Promise.reject('error')
.then((data => console.log(data))
.catch(err => console.log(err))
Promise.reject(10)
.then(data => {
console.log(data);
return 20;
})
.catch(error => {
console.log(error);
return 30;
})
.then(data => {
console.log(data);
});
// 10 30
finally
function requestData() {
return Promise.resolve(10)
.then(data => data + 20)
.catch(error => console.log(error))
.finally(() => console.log("finished"))
}
requestData().then(data => console.log(data))
// finished
// 30