How to Use then and catch in JavaScript Promises
In JavaScript,
then is used to handle the successful result of a promise, while catch handles any errors that occur. You attach then and catch methods to a promise to run code after it finishes or fails.Syntax
A promise uses then to run code when it succeeds and catch to run code when it fails. You write them like this:
promise.then(successHandler)runssuccessHandlerif the promise resolves.promise.catch(errorHandler)runserrorHandlerif the promise rejects.
javascript
promise.then(result => {
// handle success
}).catch(error => {
// handle error
});Example
This example shows a promise that resolves successfully and how then and catch handle the result or error.
javascript
const myPromise = new Promise((resolve, reject) => { const success = true; if (success) { resolve('Promise succeeded!'); } else { reject('Promise failed!'); } }); myPromise .then(message => { console.log('Success:', message); }) .catch(error => { console.log('Error:', error); });
Output
Success: Promise succeeded!
Common Pitfalls
One common mistake is forgetting to add catch, which means errors go unnoticed. Another is putting code that might fail inside then without handling errors properly. Also, chaining multiple then calls without returning promises can cause unexpected behavior.
javascript
/* Wrong: No catch to handle errors */ const p1 = Promise.reject('Oops!'); p1.then(result => { console.log('Result:', result); }); /* Right: Add catch to handle errors */ const p2 = Promise.reject('Oops!'); p2.then(result => { console.log('Result:', result); }).catch(error => { console.log('Caught error:', error); });
Output
Caught error: Oops!
Quick Reference
Use this quick guide to remember how then and catch work:
| Method | Purpose | Input | Output |
|---|---|---|---|
| then | Handles successful promise result | Function with resolved value | Returns a new promise |
| catch | Handles promise rejection (errors) | Function with error reason | Returns a new promise |
Key Takeaways
Use then to handle successful promise results.
Always add catch to handle errors and avoid silent failures.
then and catch return new promises, enabling chaining.
Errors inside then also trigger the next catch in the chain.
Proper chaining ensures clear, readable asynchronous code.