JavaScript Interview Question #80
How do then(), catch(), and finally() work with Promises?
Promises, Async/Await, Fetch & Modern JavaScript Mid-Level Intermediate
Quick Interview Answer
then registers handlers for successful Promise results and returns a new Promise, enabling chaining. catch registers a rejection handler and is effectively a convenient way to handle errors from the preceding chain.
Detailed Explanation
then registers handlers for successful Promise results and returns a new Promise, enabling chaining. catch registers a rejection handler and is effectively a convenient way to handle errors from the preceding chain.
finally registers code that runs when the Promise settles regardless of success or failure. It is commonly used for cleanup such as hiding a loading indicator.
Code Example
loadData()
.then(data => {
console.log(data);
return processData(data);
})
.catch(error => {
console.error(error);
})
.finally(() => {
console.log("Finished");
});