[JavaScript] Promise

C____JIN·2022년 12월 1일
0

JavaScript

목록 보기
5/5
post-thumbnail

Promise란?

자바 스크립트의 비동기 처리에 사용되는 객체

Promise의 상태

  • Pending(대기) : 비동기 처리 로직이 완료되지 않은 상태
  • Fulfilled(이행) : 비동기 처리가 완료되어 promise가 결과 값을 반환한 상태
  • Rejected(실패) : 비동기 처리가 실패하거나 오류가 발생한 상태
function getData() {
  return new Promise(function(resolve, reject) {	// promise 객체를 생성 (pending 상태)
    $.get('url 주소/products/1', function(response) {
      if (response) {
        resolve(response);	// response가 있다면 reslove (fulfilled 상태)
      }
      reject(new Error("Request is failed"));	// response가 없으면 reject (rejected 상태)
    });
  });
}

// 위 $.get() 호출 결과에 따라 'response' 또는 'Error' 출력
getData().then(function(data) {
  console.log(data); // response 값 출력
}).catch(function(err) {
  console.error(err); // Error 출력
});

Reference

https://joshua1988.github.io/web-development/javascript/promise-for-beginners/

profile
개발 블로그🌐 개발일지💻

0개의 댓글