[JS] Promise와 async/await

Subin Ryu·2024년 11월 20일
0
post-thumbnail

Promise와 async/await

  1. Promise
  2. async/await
  3. 사용하기

Promise

  • 비동기 작업의 완료/실패를 관리하는 객체

  • 세 가지 상태
    • pending (대기 상태) : 아직 작업이 완료되지 않음.
    • fulfilled (이행 상태): 작업이 성공적으로 완료되었을 때. 결과 값(value)을 가짐.
    • rejected (거부 상태): 작업이 실패했을 때. 에러 정보(reason)를 가짐.

  • 구조
    • Promise는 생성자 함수로 만들어지며, 비동기 작업을 처리할 콜백 함수(executor)를 받음.
    • 이 콜백 함수는 두 개의 인수인 resolvereject를 가짐.
    • Promise 생성시 executor 자동으로 실행됨.

  • 주요 메서드
    • .then(onFulfilled): 작업 성공 시 호출될 콜백.
    • .catch(onRejected): 작업 실패 시 호출될 콜백.
    • .finally(onFinally): 작업 성공/실패 여부에 상관없이 항상 실행되는 콜백.

  • 예제 코드
    const promise = new Promise((resolve, reject) => {
    const success = true;
    if (success) {
      resolve("Success!");
    } else {
      reject(new Error("Error!")); // new Error 권장
    }
    });
    promise
    .then((result) => console.log(result)) // 성공 시 실행
    .catch((error) => console.error(error)) // 실패 시 실행
    .finally(() => console.log("Done")); // 항상 실행

  • 재미있는 promise chaining 예제 코드 from 출처 드림코딩
    const getHen = () =>
      new Promise((resolve,reject) => {
        setTimeout(() => resolve('🐓'), 1000);
      });
    const getEgg = hen =>
      new Promise((resolve,reject) => {
        setTimeout(() => reject(new Error(`error! ${hen} => 🥚`)),1000);
      });
    const cook = egg =>
      new Promise((resolve,reject) => {
        setTimeout(() => resolve(`${egg} => 🍳`), 1000);
      });
    getHen() //
      .then(getEgg)
      .catch(error => {
        return `🥖`; // reject 결과를 에러대신 🥖로 대체
      })
      .then(cook)
      .then(console.log) // 🥖 => 🍳
      .catch(console.log)

async/await

  • Promise를 처리하는 더 직관적인 문법

  • async 함수: 항상 Promise를 반환.
    내부에서 반환한 값은 자동으로 resolve 됨.

  • await 키워드: Promise가 해결될 때까지 대기하고, 결과를 반환.

  • 예제 코드

async function fetchData() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}

fetchData();

작동 방식:
1. async 함수가 호출되면 내부의 비동기 작업이 실행되고, Promise가 반환됨.
2. await은 Promise가 해결될 때까지 실행을 일시 중단하고 해결되면 결과를 반환하고 코드 실행을 계속함.
3. 오류가 발생하면 catch 블록에서 처리됨.

사용하기

// promise 보다 간단한 async/await 사용
async function getApple() {
  await delay(1000);
  return '🍎';
}

async function getBanana() {
  await delay(1000);
  return '🍌';
}

// 여러 비동기 작업 병렬적으로 실행할땐 promise 메서드 사용
function pickAllFruits() {
  return Promise.all([getApple(),getBanana()]).then(fruits => fruits.join(' + '));
}

pickAllFruits().then(console.log) // 🍎 + 🍌

function pickOnlyOne() {
  return Promise.race([getApple(),getBanana()]);
}

pickOnlyOne().then(console.log) // 🍌
  • 명시적 Promise 생성이 필요하지 않은 비동기 작업
    fetch
    axios 같은 HTTP 라이브러리
    async 함수 (자동으로 Promise를 반환)
    Promise.all / Promise.allSettled / Promise.race
profile
개발블로그입니다.

0개의 댓글