then : Promise가 정상적으로 수행되어 callback 함수 resolve를 통해 나온 결과를 전달한다.
then 의 callback 함수는 onfulfilled?, onrejected? 가 존재한다.
onfulfilled? : (value: any) => any | PromiseLike<any>
onrejected? : (reason: any) => PromiseLike<never>
then 은 최종적으로 Promise 객체를 반환한다. : return Promise<any> ★
then<TResult1 = T, TResult2 = never>
(
onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null
, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null
)
:Promise<TResult1 | TResult2>;
const promise = new Promise((resolve, reject) => {
console.log('doing something...');
setTimeout(() => {
resolve('ellie');
// reject(new Error('no network'));
}, 2000);
});
promise
.then((value) => {
console.log(value);
})
.catch((error) => {
console.log(error);
})
.finally(() => {
console.log('finally'); // 성공여부와 상관없이 마지막에 출력된다.
});
// promise.then 에서 '최종적으로' 반환하는 값이 Promise 객체이기 때문에 뒤에
// .catch 가 올 수 있다. ★
// ex) map.join() 처럼
catch<TResult = never>
(
onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null
)