Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 2 of 10 · Promises and Async/Await
Interview question

How do .then(), .catch(), and .finally() work in Promise chains? Promise chains में .then(), .catch(), और .finally() कैसे काम करते हैं?

Answer

These methods let you handle a promise's eventual result. Each returns a new Promise, which is what enables chaining.

MethodRuns whenPurpose
.then()Promise fulfillsHandle success value, can chain more logic
.catch()Promise rejects (anywhere upstream)Handle errors
.finally()Always, regardless of outcomeCleanup logic (hide spinner, close connection)
function fetchUser(id) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (id > 0) resolve({ id, name: 'John' });
            else reject(new Error('Invalid ID'));
        }, 500);
    });
}

fetchUser(1)
    .then(user => {
        console.log('User:', user);
        return user.id; // returned value passed to next .then()
    })
    .then(id => {
        console.log('ID was:', id);
    })
    .catch(error => {
        console.log('Error:', error.message); // catches errors from ANY step above
    })
    .finally(() => {
        console.log('Request finished'); // always runs
    });

// A .catch() placed early stops error propagation for subsequent .then()
fetchUser(-1)
    .then(user => console.log(user)) // skipped due to rejection
    .catch(error => {
        console.log('Caught:', error.message);
        return 'default user'; // recovers the chain
    })
    .then(value => console.log('Continues with:', value)); // runs normally

ये methods promise के eventual result को handle करने देते हैं। हर method एक नया Promise return करता है, इसीलिए chaining possible है।

Methodकब चलता हैउद्देश्य
.then()Promise fulfill होने परSuccess value handle करना
.catch()Promise reject होने परErrors handle करना
.finally()हमेशाCleanup logic
function fetchUser(id) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (id > 0) resolve({ id, name: 'John' });
            else reject(new Error('Invalid ID'));
        }, 500);
    });
}

fetchUser(1)
    .then(user => {
        console.log('User:', user);
        return user.id;
    })
    .then(id => console.log('ID was:', id))
    .catch(error => console.log('Error:', error.message))
    .finally(() => console.log('Request finished'));

Was this answer clear?