본문 바로가기
JavaScript

[JS] Promise 이해

by watergrace2u 2020. 10. 5.
반응형
SMALL

- JS 비동기 처리에 사용되는 객체

(JS비동기 처리: 특정 코드의 실행이 완료될 때까지 기다리지 않고 다음 코드를 먼저 수행하는 js의 특성)

- 주로 서버에서 받아온 데이터를 화면에 표시할 때 사용

- 콜백 지옥을 해결하기 위해 사용(async도 사용 가능)

- 여러개의 프로미스를 연결하여 사용 가능


<프로미스의 3가지 상태(states)>

new Promise()로 프로미스 객체를 생성하고 종료될 때까지 3가지 상태를 갖는다.

  • Pending(대기) : 비동기 처리 로직이 아직 완료되지 않은 상태
  • Fulfilled(이행) : 비동기 처리가 완료되어 프로미스가 결과 값을 반환해준 상태
  • Rejected(실패) : 비동기 처리가 실패하거나 오류가 발생한 상태
function getData(callback) {
  // new Promise() 추가
  return new Promise(function(resolve, reject) {
    $.get('url 주소/products/1', function(response) {
      // 데이터를 받으면 resolve() 호출
      resolve(response);
    });
  });
}

// getData()의 실행이 끝나면 호출되는 then()
getData().then(function(tableData) {
  // resolve()의 결과 값이 여기로 전달됨
  console.log(tableData); // $.get()의 reponse 값이 tableData에 전달됨
});

1. new Promise() 를 하면 대기 상태가 된다.

2. 콜백 함수의 인자 resolve를 실행하면 이행(완료)상태가 된다.

3. 이행 상태가 되면 then()을 이용하여 처리 결과 값을 받을 수 있다.

 

Rejected(실패)

- reject를 호출하면 실패 상태가 된다.

- 실패 상태가 되면 실패한 이유(실패 처리의 결과 값)를 catch()로 받을 수 있다.

function getData() {
  return new Promise(function(resolve, reject) {
    reject(new Error("Request is failed"));
  });
}

// reject()의 결과 값 Error를 err에 받음
getData().then().catch(function(err) {
  console.log(err); // Error: Request is failed
});

cf. 프로미스 처리 흐름 - MDN

 

예제>

function getData() {
  return new Promise(function(resolve, reject) {
    $.get('url 주소/products/1', function(response) {
      if (response) {
        resolve(response);
      }
      reject(new Error("Request is failed"));
    });
  });
}

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

<여러 개의 프로미스 연결(Promise Chaining)>

- then() 메서드를 호출하면 새로운 프로미스 객체가 반환되기 때문에 아래와 같은 코드 작성 가능

ex1> 

new Promise(function(resolve, reject){
  setTimeout(function() {
    resolve(1);
  }, 2000);
})
.then(function(result) {
  console.log(result); // 1
  return result + 10;
})
.then(function(result) {
  console.log(result); // 11
  return result + 20;
})
.then(function(result) {
  console.log(result); // 31
});

ex2>

getData(userInfo) // userInfo-> 사용자 정보가 담긴 객체
  .then(parseValue) // 각각 프로미스를 반환해주는 함수
  .then(auth)
  .then(diaplay);

<프로미스의 에러 처리 방법>

- 프로미스의 reject() 가 호출되어 실패 상태가 된 경우에 실행된다.

1. then()의 두 번째 인자로 에러 처리

getData().then(
  handleSuccess,
  handleError
);

2. catch()를 이용(추천!!)

getData().then().catch();
// catch()로 오류를 감지하는 코드
function getData() {
  return new Promise(function(resolve, reject) {
    resolve('hi');
  });
}

getData().then(function(result) {
  console.log(result); // hi
  throw new Error("Error in then()");
}).catch(function(err) {
  console.log('then error : ', err); // then error :  Error: Error in then()
});

 

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

반응형
LIST

'JavaScript' 카테고리의 다른 글

모던 JS 튜토리얼 정리 1  (0) 2020.11.12
[JS] apply 사용  (0) 2020.10.28
[JS] 클로저 주의사항  (0) 2020.10.28
[JS] Fetch API 사용하기  (0) 2020.10.05
[JS] async와 await 이해  (0) 2020.10.05

댓글