In JavaScript, promises are designed to be chainable, allowing you to perform a sequence of asynchronous operations and handle errors at various points in the chain. This means that a catch() block can be used at different points in the promise chain after any of the then() blocks, as shown in the example below:
function fetchSomething() {
return new Promise((resolve, reject) => {
setTimeout(() => {
// Simulate an error
reject("An error occurred");
}, 1000);
});
}
fetchSomething()
.then(result => {
console.log('Success:', result);
})
.catch(error => {
console.error('Error 1:', error);
// You can recover or continue the chain here
return 'Recovered from error';
})
.then(result => {
console.log('Continuation:', result);
// Simulate another error
throw new Error('Another error occurred');
})
.catch(error => {
console.error('Error 2:', error);
// Handle the second error
});
When you run this code, it will produce the following output:
// Error 1: An error occurred
// Continuation: Recovered from error
// Error 2: Error: Another error occurred
In this example, the following happens:
- The
fetchSomething()function returns a promise that rejects with an error message after a timeout; - The first
catch()block catches the initial error, logs it, and returns a recovery value; - The second
then()block (after the firstcatch()) continues the chain; - Another error is simulated by throwing an error in the second
then()block; - The second
catch()block catches the second error and logs it.