The then() and catch() are methods used in JavaScript Promise objects to handle asynchronous operations and their results. Where then()
is called on a Promise after it has been resolved successfully, while catch()
is called on a Promise after it has been rejected with an error.
fetch('https://api.example.com/data')
.then(response => {
// Do something with the response data
console.log(response);
})
.catch(error => {
// Handle any errors that occurred during the fetch operation
console.error(error);
});
The then() is a method called on a Promise object after it has resolved successfully. It takes one or two optional callback functions as arguments: the first function is called with the resolved value of the Promise, while the second function is called with any error during the Promise’s execution.
Then catch JavaScript example
Simple example code of using then()
and catch()
with a Promise to perform a simple calculation:
<!DOCTYPE html>
<html>
<body>
<script>
const calculate = (a, b) => {
return new Promise((resolve, reject) => {
if (typeof a !== 'number' || typeof b !== 'number') {
reject('Invalid input: both arguments must be numbers');
} else {
const result = a + b;
resolve(result);
}
});
};
calculate(2, 3)
.then(result => {
console.log('The result is:', result);
})
.catch(error => {
console.error('An error occurred:', error);
});
</script>
</body>
</html>
Output:
Comment if you have any doubts or suggestions on this JS exception handling the topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version