Promise와 Async/Await의 차이

oversleep·2025년 2월 4일
post-thumbnail
  1. 기본 문법 차이:
// Promise 방식
function getData() {
    return fetch('https://api.example.com/data')
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => console.error(error));
}

// Async/Await 방식
async function getData() {
    try {
        const response = await fetch('https://api.example.com/data');
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error(error);
    }
}

주요 차이점:
1. 가독성

  • Promise는 .then() 체인이 길어지면 코드가 복잡해짐
  • Async/Await는 일반 동기 코드처럼 읽기 쉬움
  1. 에러 처리

    • Promise는 .catch()로 처리
    • Async/Await는 try-catch 사용 가능
  2. 여러 작업 처리:

// Promise 방식
function getMultipleData() {
    return Promise.all([
        fetch('/api/data1'),
        fetch('/api/data2'),
        fetch('/api/data3')
    ])
    .then(responses => Promise.all(responses.map(r => r.json())))
    .then(([data1, data2, data3]) => {
        console.log(data1, data2, data3);
    });
}

// Async/Await 방식
async function getMultipleData() {
    try {
        const [response1, response2, response3] = await Promise.all([
            fetch('/api/data1'),
            fetch('/api/data2'),
            fetch('/api/data3')
        ]);
        
        const [data1, data2, data3] = await Promise.all([
            response1.json(),
            response2.json(),
            response3.json()
        ]);
        
        console.log(data1, data2, data3);
    } catch (error) {
        console.error(error);
    }
}
  1. 실제 사용 예시로 보는 차이:
// Promise 방식의 로그인
function login(username, password) {
    return fetch('/api/login', {
        method: 'POST',
        body: JSON.stringify({ username, password })
    })
    .then(response => response.json())
    .then(user => {
        return fetch(`/api/profile/${user.id}`)
            .then(response => response.json())
            .then(profile => ({
                user,
                profile
            }));
    })
    .catch(error => {
        console.error('로그인 실패:', error);
        throw error;
    });
}

// Async/Await 방식의 로그인
async function login(username, password) {
    try {
        const userResponse = await fetch('/api/login', {
            method: 'POST',
            body: JSON.stringify({ username, password })
        });
        const user = await userResponse.json();
        
        const profileResponse = await fetch(`/api/profile/${user.id}`);
        const profile = await profileResponse.json();
        
        return { user, profile };
    } catch (error) {
        console.error('로그인 실패:', error);
        throw error;
    }
}

정리하면:

  • Promise는 비동기 작업의 기본이 되는 객체
  • Async/Await는 Promise를 더 편하게 사용할 수 있게 해주는 문법
  • Async/Await도 내부적으로는 Promise를 사용함
  • Async/Await가 더 읽기 쉽고 디버깅하기 쉬움
  • 복잡한 비동기 로직을 다룰 때는 Async/Await가 더 유리

어떤 것을 사용할지는 상황에 따라 다름:

  • 간단한 비동기 작업: Promise도 충분
  • 복잡한 비동기 작업: Async/Await 권장
  • 오래된 코드 유지보수: 기존 방식 유지
  • 새로운 코드 작성: Async/Await 권장
profile
궁금한 것, 했던 것, 시행착오 그리고 기억하고 싶은 것들을 기록합니다.

0개의 댓글