카테고리 없음

[JavaScript] Promise

썽연 2021. 10. 14. 13:06
728x90

Promise는 비동기작업을 조금 더 편하게 처리할 수 있도록 하는 ES6에 도입된 기능

 

이전에는 비동기 작업을 콜백함수로 처리하여 코드가 난잡해졌음

콜백함수 예시

function increaseAndPrint(n, callback) {
  setTimeout(() => {
    const increased = n + 1;
    console.log(increased);
    if (callback) {
      callback(increased);
    }
  }, 1000);
}

increaseAndPrint(0, n => {
  increaseAndPrint(n, n => {
    increaseAndPrint(n, n => {
      increaseAndPrint(n, n => {
        increaseAndPrint(n, n => {
          console.log('끝!');
        });
      });
    });
  });
});

똑같은 함수를 같은 함수 안에 여러번호출하여

콜백지옥 이라고 부르는 코드발생

 

콜백 지옥의 코드 해결법 = > Promise

 

const myPromise = new Promise((resolve, reject) => {
  // 구현..
})

resolve는 성공할 때 호출,

reject는 실패할 때 호출하는 값이다.

성공할 때는 상관없을 수 있으나,

실패할 때의 코드를 보면

function increaseAndPrint(n) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const value = n + 1;
      if (value === 5) {
        const error = new Error();
        error.name = 'ValueIsFiveError';
        reject(error);
        return;
      }
      console.log(value);
      resolve(value);
    }, 1000);
  });
}

increaseAndPrint(0)
  .then(n => {
    return increaseAndPrint(n);
  })
  .then(n => {
    return increaseAndPrint(n);
  })
  .then(n => {
    return increaseAndPrint(n);
  })
  .then(n => {
    return increaseAndPrint(n);
  })
  .then(n => {
    return increaseAndPrint(n);
  })
  .catch(e => {
    console.error(e);
  });

이 코드가

promise를 통해

function increaseAndPrint(n) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const value = n + 1;
      if (value === 5) {
        const error = new Error();
        error.name = 'ValueIsFiveError';
        reject(error);
        return;
      }
      console.log(value);
      resolve(value);
    }, 1000);
  });
}

increaseAndPrint(0)
  .then(increaseAndPrint)
  .then(increaseAndPrint)
  .then(increaseAndPrint)
  .then(increaseAndPrint)
  .then(increaseAndPrint)
  .catch(e => {
    console.error(e);
  });

조금 더 간결한 코드로 바뀔 수 있다.

promise를 사용하면서 에러를 잡을 때는 꼭 catch를 쓸 것을 추천한다.

then으로 에러를 처리하면,

then()의 첫 번째 콜백함수 내부에서 오류가 나는 경우 오류를 제대로 잡아내지 못한다.

 

하지만 promise를 쓰면서의 단점도 있음.

=> 에러를 잡을 때 몇번째에서 발생하는지 알아내기 어렵고

특정 조건에 따라 분기를 나누는 작업이 어려움!

특정 값 공유해가면서 작업 처리가 까다롭다.

 

 

해결법 => async/await 

728x90