javascript - 비동기 실행과 Promise 객체

JM·2022년 4월 1일
post-thumbnail

codeit 사이트에서 공부한 내용을 정리했습니다.

쉽지 않다! 여러 번 코드를 작성하다 보면 익숙해지겠지..?

rejected 상태

fetch('https://learn.codeit.kr/api/interviews/summer')
  .then((response) => response.text(), (error) => {console.log(error)})
  .then((result) => {console.log(result)})

catch 메소드

위에서 error를 catch를 사용해서 다룰 수 있다.
.then(undefined, (error) => {console.log(error)}) 와 같은 결과를 보여준다.

fetch('https://learn.codeit.kr/api/interviews/summer')
  .then((response) => response.text())
  .catch((error) => {console.log(error)}) // .then(undefined, (error) => {console.log(error)})
  .then((result) => {console.log(result)})

실무에서는 catch 메소드를 보통 마지막에 작성한다.
에러 발생을 잡을 수 있지만, 특정 에러가 어디서 발생한 것인지를 알려면 해당 에러 객체를 조사를 위해 따로 코드 작성이 필요합니다.

.catch((error) => { 
    if(error.message === 'A'){

    }else if(error.message === 'B'){

    }else if(error.message === 'C'){

    }else{

    }
  });

만약, 에러가 발생해도 기존의 보여줄 수 있는 것을 보여주기 위해서는 중간에 catch 메소드를 여러 개 작성하기도 한다.

fetch('https://learn.codeit.kr/api/interviews/summer')
  .then((response) => response.json())
  .then((result) => {console.log(result)})
  .catch((error) => {
    // 미리 저장해둔 일반 뉴스를 보여주기  
    const storedGeneralNews = getStoredGeneralNews();
    return storedGeneralNews;
  })
  .then((result) => { /* 화면에 표시 */ }) 
  .catch((error) => { /* 에러 로깅 */ })

finally 메소드

promise가 어떤 상태이든 상관 없이 출력하고 싶을 때 사용하는 메소드이다.
catch 메소드 보다 더 뒤에 작성을 한다.

fetch('https://learn.codeit.kr/api/interviews/summer')
  .then((response) => response.text())
  .catch((error) => {console.log(error)}) // .then(undefined, (error) => {console.log(error)})
  .then((result) => {console.log(result)})
  .finally(() => {console.log('exit')})

Promise 객체는 왜 등장했을까?

함수에 콜백을 직접 넣는 형식은 콜백 헬(callback hel)이라고 하는 문제를 일으킬 수 있다.

// 콜백 헬 예시
fetch('https://first.com', (response) => {
  // Do Something
  fetch('https://second.com', (response) => {
    // Do Something
    fetch('https;//third.com', (response) => {
      // Do Something
      fetch('https;//fourth.com', (response) => {
        // Do Something
      });
    });
  });
});
fetch('https://first.com')
  .then((response) => {
    // Do Something 
    return fetch('https://second.com');
  })
  .then((response) => {
    // Do Something 
    return fetch('https://third.com');
  })
  .then((response) => { 
    // Do Something 
    return fetch('https://third.com');
  });

직접 Promise 만들기

전통적인 형식의 비동기 실행 함수를 사용하는 코드를, Promise 기반의 코드로 변환하기 위해 Promise 객체를 직접 만드는 경우가 많다.

const p = new Promise((resole, reject) =>
{
  setTimeout(() => {resolve('success');}, 2000);
});
p.then((result) => {console.log(result); }); 
const p = new Promise((resolve, reject) => {
  setTimeout(() => {reject(new Error('fail'))}, 2000);
})

p.catch((error)=> {console.log(error)});

상태가 결정된 Promise 객체 만들기

처음부터 fulfilled 또는 rejected 상태인 Promise 객체를 만들 수 있다.

const testResolve = Promise.resolve('test');
const testReject = Promise.reject(new Error('fail'));

const testPromise = new Promise((resolve, reject) => {
	console.log('test');
})

all, race / allSettled, any

all

  • 여러 Promise 객체의 작업 성공 결과를 기다렸다가 모두 한 번에 취합
  • 만약 하나라도 rejected 상태가 되면 실패한 것으로 간주한다.

race

  • 여러 Promise 객체들 중에서 가장 먼저 fulfilled 또는 rejected 상태가 된 Promise 객체와 동일한 생태의 결과를 갖게 된다.

allSettled

  • 여러 Promise 객체들이 settled 상태가 되기만 하면 된다. 즉, 모든 Promise 객체가 fulfilled 또는 rejected 되면 성공한 것으로 간주한다.
  • fulfilled와 rejected 를 묶어서 settled 상태라고 한다.

any

  • 여러 Promise 객체 중 하나라도 fulfiiled 가 되면 성공한 것으로 간주하고 모두 rejected 상태가 되면 AggregateError 라고 하는 에러를 출력한다.
profile
초조해하지 말자! 나는 충분히 할 수 있다! 인생은 길다!

0개의 댓글