공부/JavaScript
Promise
래코드
2022. 9. 1. 00:24
# 01. Promise
MDN 정의 : The promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
: Promise 오브젝트는 비동기적으로 완료된 이벤트의 성공 혹은 실패와 그 결과 값을 알려줌
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Promise는 Callback 지옥에서 벗어나 깔끔한 함수형 프로그래밍을 할 수 있게 도와줌.
A Promise is in one of these states: 진행중, 성공, 실패의 3가지 상태값을 가짐 !
- pending: initial state, neither fulfilled nor rejected.
- fulfilled: meaning that the operation was completed successfully.
- rejected: meaning that the operation failed.
Promise 함수는 Promise 객체를 return하고 사용은 아래와 같이 할 수 있음
function 시간이걸리는함수(시간){
return new Promise((resolve, reject) => {
if(false){
reject(new Error('에러가 남!'));
}
setTimeout(resolve, 시간);
});
}
시간이걸리는함수(시간) //
.then(성공한다면)
.catch(실패한다면)
.finally(성공하든 실패하든 호출)