Promise

:D ·2021년 12월 4일
1

JavaScript✌️

목록 보기
12/14
post-thumbnail

Promise란?

Promise는 자바스크립트 비동기 처리에 사용되는 객체입니다.

Promise가 왜 필요할까요?

  1. 콜백 헬

비동기 함수의 처리 결과를 가지고 다른 비동기 함수를 호출해야 하는 경우, 함수의 호출이 중첩(nesting)이 되어 복잡도가 높아지는 현상이 발생하는데 이를 콜백 헬이라고 합니다.

  1. 에러처리
try {
  setTimeout(() => { throw new Error('Error!'); }, 1000);
} catch (e) {
  console.log('에러를 캐치하지 못한다..');
  console.log(e);
}

크게 2가지 문제점 때문에 Promise가 생겨났습니다.

어떻게 Promise를 생성할까?

// Promise 객체의 생성
const promise = new Promise((resolve, reject) => {
  // 비동기 작업을 수행한다.

  if (/* 비동기 작업 수행 성공 */) {
    resolve('result');
  }
  else { /* 비동기 작업 수행 실패 */
    reject('failure reason');
  }
});

Promise의 에러처리

then()의 두 번째 인자로 에러를 처리 방법과 catch()로 에러를 처리하는방법이 있습니다. 가급적이면 catch()로 에러 처리를 하는것이 좋습니다 :D

  1. then()의 두 번째 인자로 에러를 처리
// then()의 두 번째 인자로는 감지하지 못하는 오류
function getData() {
  return new Promise(function(resolve, reject) {
    resolve('hi');
  });
}

getData().then(function(result) {
  console.log(result);
  throw new Error("Error in then()"); // Uncaught (in promise) Error: Error in then()
}, function(err) {
  console.log('then error : ', err);
});
  1. 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()
});

첫번째 경우 then()의 첫 번째 콜백 함수 내부에서 오류가 나는 경우 오류를 제대로 잡아내지 못합니다. 즉, 더 많은 에러 처리를 위해 catch()로 에러 처리를 하는것이 좋습니다.

프로미스의 정적 메소드

  1. Promise.resolve/Promise.reject
  2. Promise.all

Promise.all 메소드는 전달받은 모든 프로미스를 병렬로 처리합니다. 모든 프로미스의 처리가 성공하면 각각의 프로미스가 resolve한 처리 결과를 배열에 담아 resolve하는 새로운 프로미스를 반환한다.

  1. Promise.race

Promise.race 메소드는 Promise.all 메소드처럼 모든 프로미스를 병렬 처리하는 것이 아니라 가장 먼저 처리된 프로미스가 resolve한 처리 결과를 resolve하는 새로운 프로미스를 반환한다.

profile
강지영입니...🐿️

0개의 댓글