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.
| Method | Runs when | Purpose |
|---|---|---|
| .then() | Promise fulfills | Handle success value, can chain more logic |
| .catch() | Promise rejects (anywhere upstream) | Handle errors |
| .finally() | Always, regardless of outcome | Cleanup 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?