JavaScript

비동기 함수를 Promise로 제어하기

2025년 10월 29일

🧩 1. Promise란?

비동기 작업의 완료(or 실패)를 나타내는 객체

Promise는 자바스크립트에서 비동기 작업의 결과를 다루는 표준 방식이에요.

서버에서 데이터를 불러오거나, 파일을 읽거나, 시간이 걸리는 작업을 수행할 때 사용됩니다.


⚙️ 2. Promise의 상태 (State)

상태의미예시
pending아직 결과가 정해지지 않은 상태서버에 요청을 보낸 직후
fulfilled작업이 성공적으로 완료된 상태응답을 잘 받음
rejected작업이 실패한 상태네트워크 오류 등 발생
const promise = new Promise((resolve, reject) => {
  const success = true;
 
  if (success) resolve("✅ 성공!");
  else reject("❌ 실패!");
});

🔁 3. Promise 사용법 (then, catch, finally)

promise
  .then((result) => {
    console.log(result); // ✅ 성공!
  })
  .catch((error) => {
    console.error(error); // ❌ 실패!
  })
  .finally(() => {
    console.log("작업 종료");
  });
메서드설명
.then()성공했을 때 실행할 콜백
.catch()실패했을 때 실행할 콜백
.finally()성공/실패 관계없이 마지막에 항상 실행

🚀 4. Promise 체이닝 (Chaining)

비동기 작업을 순차적으로 연결할 수 있습니다.

getUser()
  .then((user) => getProfile(user.id))
  .then((profile) => showProfile(profile))
  .catch((error) => console.error(error));

이런 식으로 연결하면, 콜백 지옥(Callback Hell)을 피하면서도

가독성 있게 비동기 로직을 이어 쓸 수 있어요.


⚠️ 5. 콜백 지옥 vs Promise

구분콜백 함수Promise
구조중첩 구조로 복잡해짐체이닝으로 깔끔함
에러 처리각 콜백마다 따로 처리.catch() 하나로 처리 가능
가독성낮음 😖높음 😎
// ❌ 콜백 지옥
getData((a) => {
  getUser(a, (b) => {
    getPosts(b, (c) => {
      console.log(c);
    });
  });
});
 
// ✅ Promise
getData()
  .then(getUser)
  .then(getPosts)
  .then(console.log);

⏳ 6. Promise는 언제 사용될까?

  • fetch(), axiosAPI 호출
  • setTimeout, setInterval 같은 비동기 타이머
  • 파일 업로드 / 다운로드
  • 브라우저의 비동기 이벤트 처리
fetch("https://api.example.com/data")
  .then((res) => res.json())
  .then((data) => console.log(data))
  .catch((err) => console.error(err));

🧠 7. Promise의 핵심 포인트 요약

✅ Promise는 비동기 작업의 성공/실패 상태를 표현하는 객체

.then, .catch, .finally로 결과를 다룬다

✅ 체이닝으로 콜백 지옥을 해결한다

✅ 모든 비동기 함수가 Promise를 반환하지는 않지만,

async/await와 함께 쓰면 훨씬 간결하게 비동기 코드를 작성할 수 있다