TIL | Promise, Async - Await, 차이점 ...

·2023년 8월 30일

TIL # WIL

목록 보기
62/65

23.08.30

1. Promise

Promise : JavaScript에서 비동기 처리에 사용되는 객체, 뜻 그대로 '약속' 이라는 의미 !

즉, 내용은 실행 되었으나 제대로 처리가 된 후에 데이터를 넘겨주고 아니면 오류를 줄 것이라는 약속이다.

Promise의 3가지 상태

  1. Pending (대기) : 비동기 처리가 완료 되지 않았을 때
  2. Fulfilled (이행) : 완료되었을 때
  3. Rejected (실패) : 오류가 발생하였을 때
cosnt fetchData = () => {
  // Promise 객체 생성
  return new Promise((resolve, reject) => {
      setTimeout(() => {
        const data = "Hello, Promise with arrow function!";
        if (data) {
          resolve(data);
        } else {
          reject("Error: Data not available.");
        }
      }, 2000);
  });
}

fetchData()
  .then(result => {
    console.log(result); // 작업이 성공했을 때 출력
  })
  .catch(error => {
    console.error(error); // 작업이 실패했을 때 출력
  });

2. Async - Await

Async - Await : 기존에 존재하는 Promise를 조금 더 간편하게 사용 할 수 있도록 도와주며 동기적으로 실행되는 것 처럼 보이게 하는 문법 => 즉, Promise의 Syntatic sugar

Q. 그렇다면 여기서 Syntatic sugar란?
A. 문법적 기능은 그대로인데(같은데) 사람이 사용하기 편하게 제공되는 프로그래밍 문법을 의미한다. 기존에 존재하던 문법을 함수 등으로 감싸서 조금 더 간편하게 바꿔서 사용할 수 있도록 도와준다.

Code after each await expression can be thought of as existing in a .then callback. In this way a promise chain is progressively constructed with each reentrant step through the function. The return value forms the final link in the chain.
=> awiat은 Promise의 then을 표현하는 또 다른 문법

즉, Promise가 resolve하거나 reject할 때 까지 async Call 내부에서 기다렸다가 결과에 오류가 없으면 그 때 result를 정상적으로 출력해준다.

const fetchData = () => {
  // Promise 객체 생성
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = "Hello, async-await with arrow function!";
      if (data) {
        resolve(data);
      } else {
        reject("Error: Data not available.");
      }
    }, 2000);
  });
}

// 매개변수 앞에 async를 적고, Promise 함수 실행 앞에 await을 적음
const main = async () => {
  try {
    const result = await fetchData();
    console.log(result);
  } catch (error) {
    console.error(error);
  }
}

main();

3. Promise와 Async - Await의 차이점

  • Promise
    .then().catch()를 사용해서 에러 핸들링을 한다. (= Rejected 잡기 !)
    Promise는 .then() 지옥의 가능성이 있어 코드가 길어지면 길어질수록 가독성이 떨어진다
  • Async - Await
    에러 핸들링 할 수 있는 기능이 없어 try-catch()문을 사용해야한다. (= Rejected 잡기 !)
    async - await은 비동기 코드가 동기 코드처럼 읽히게 해주어 코드 흐름을 이해 하기 쉽다.

4. 레퍼런스

참고 블로그
참고 블로그 2
참고 블로그 3

0개의 댓글