💻 Programming

Promise

Promise

An object representing the eventual completion/failure of an asynchronous operation. Handled with then, catch, and finally. The basis of async/await.

📖 Detailed Explanation

A Promise is an object in JavaScript that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Formally introduced in ES6 (ECMAScript 2015), it resolved the complexity of callback-based asynchronous handling and enabled more intuitive asynchronous programming. A Promise represents a promise to "provide a result at some point in the future."

A Promise has three states. pending (waiting) is the initial state, in which it has been neither fulfilled nor rejected. fulfilled is the state in which the operation completed successfully, and rejected is the state in which the operation failed. Once a Promise becomes fulfilled or rejected, its state does not change, and this is called settled.

The core strength of Promise is chaining. Because the then() method returns a new Promise, consecutive asynchronous operations can be processed sequentially in the form .then().then().catch(). Errors can be handled in one place with catch(), and code that should run regardless of success or failure can be defined with finally(), which resolves callback hell.

async/await, introduced in ES2017, is syntactic sugar that lets you write Promise-based code more like synchronous code. An async function always returns a Promise, and the await keyword pauses execution until the Promise is settled. Because it still uses Promises internally, understanding how Promises work is the foundation for using async/await correctly.

💻 Code Example

// 1. Promise 생성하기
function fetchUser(userId) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (userId > 0) {
                resolve({ id: userId, name: '홍길동', email: 'hong@example.com' });
            } else {
                reject(new Error('유효하지 않은 사용자 ID'));
            }
        }, 1000);
    });
}

// 2. Promise 체이닝 (then, catch, finally)
fetchUser(1)
    .then(user => {
        console.log('사용자 조회 성공:', user.name);
        return fetchUserPosts(user.id);  // 다음 Promise 반환
    })
    .then(posts => {
        console.log('게시물 수:', posts.length);
        return posts.map(p => p.title);
    })
    .then(titles => {
        console.log('게시물 제목들:', titles);
    })
    .catch(error => {
        // 체인 어디서든 발생한 에러를 여기서 처리
        console.error('오류 발생:', error.message);
    })
    .finally(() => {
        console.log('작업 완료 (성공/실패 무관)');
    });


// 3. Promise.all - 여러 Promise 병렬 실행
async function fetchDashboardData() {
    const [user, posts, notifications] = await Promise.all([
        fetchUser(1),
        fetchUserPosts(1),
        fetchNotifications(1)
    ]);
    // 세 요청이 동시에 시작되어 가장 느린 요청 시간만 소요
    console.log('대시보드 데이터:', { user, posts, notifications });
}


// 4. Promise.allSettled - 실패해도 모든 결과 받기
const promises = [
    fetchUser(1),      // 성공
    fetchUser(-1),     // 실패
    fetchUser(2)       // 성공
];

Promise.allSettled(promises).then(results => {
    results.forEach((result, i) => {
        if (result.status === 'fulfilled') {
            console.log(`Promise ${i}: 성공`, result.value);
        } else {
            console.log(`Promise ${i}: 실패`, result.reason.message);
        }
    });
});


// 5. async/await으로 동기 코드처럼 작성
async function processUser(userId) {
    try {
        const user = await fetchUser(userId);
        console.log('사용자:', user.name);

        const posts = await fetchUserPosts(user.id);
        console.log('게시물 수:', posts.length);

        // 병렬 실행이 필요하면 Promise.all 사용
        const [comments, likes] = await Promise.all([
            fetchComments(posts[0].id),
            fetchLikes(posts[0].id)
        ]);

        return { user, posts, comments, likes };
    } catch (error) {
        console.error('처리 중 오류:', error.message);
        throw error;  // 에러 재전파
    }
}

// async 함수 호출 (Promise 반환)
processUser(1).then(data => console.log('완료:', data));

🗣️ Say It Like This in Practice

💬 In an Interview (Promise vs Callback)
"A callback receives an asynchronous result by passing a function as an argument, but nesting them leads to callback hell. A Promise can be written flatly with then chaining, and errors can be handled in one place with catch. Also, parallel processing can be implemented easily with Promise.all, which makes it more flexible than callbacks."
💬 In a Code Review (Error Handling)
"This async function has no try-catch. If an await rejects, the error propagates and an unhandled rejection warning occurs. Please wrap it in try-catch, or add .catch() on the calling side. In Node.js, it's also a good idea to set up a global handler with process.on('unhandledRejection')."
💬 In a Meeting
"These three API calls don't depend on each other, so running them in parallel with Promise.all instead of sequential await can cut the response time from 3 seconds to 1 second. However, if even one fails, the whole thing rejects, so if you want to tolerate partial failures, you need to use Promise.allSettled."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Unhandled Promise Rejection

If a reject occurs in a Promise and it is not handled with catch() or try-catch, a warning is raised. In Node.js 15+, the process may terminate. Always end every Promise chain with .catch(), or use try-catch inside async functions.

❌
Sequential await vs Parallel Execution

Awaiting independent asynchronous operations sequentially makes things unnecessarily slow. Instead of `await a(); await b();`, run them in parallel with `await Promise.all([a(), b()]);`. However, when order matters or the earlier result is needed for the later call, sequential execution is correct.

❌
Beware of async Function Return Values

An async function always returns a Promise. `return value` is equivalent to `Promise.resolve(value)`. If you use async in a forEach callback, the returned Promise is ignored, so use a for...of loop or Promise.all(arr.map(...)).

✅
Choosing the Right Pattern

For simple asynchronous flows, async/await offers better readability. Use Promise.all for parallel processing, Promise.allSettled to tolerate partial failures, and Promise.race if you only need the fastest result. For event-based code, callbacks are still appropriate.

🔗 Related Terms

📚 Learn More