본문 바로가기

공부/JavaScript

Promise

# 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(성공하든 실패하든 호출)

 

'공부 > JavaScript' 카테고리의 다른 글

reduce 배열에서 쓸 수 있는 고차함수  (0) 2022.11.11
Class - this 바인딩  (0) 2022.11.04
Truthy & Falsy  (0) 2022.09.12
async, await  (0) 2022.09.01
JavaScript 챌린지 (1)  (0) 2022.08.04