Middle
The chain immediately becomes rejected, the first .then is skipped. The first .catch catches the error Output: Catch 1: Error1 Returns 'Other value', turning the error into a successful result. The next .then receives 'Other value' Output: Then 2: Other value Then throws a new error: throw new Error('Second error') The chain again becomes rejected. The second .catch catches the second error Output: Catch 2: Second error Returns nothing → result is undefined. The last .then receives undefined Output: Then 3: undefined Greetings! ("Error!") is a promise that immediately rejects with the error "Error!" .then(1) — is skipped because the promise is in rejected state .catch(1) — catches the error, outputs "Catch 1: Error!" and returns "DATA RETURNED" .then(2) — receives "DATA RETURNED", outputs "Ticker ? DATA RETURNED" and throws a new error "Second error" .catch(2) — catches the second error, outputs "Catch 2: Second error" .then(3) — receives undefined (since the previous catch returned nothing), outputs "then 3: undefined"
sobes.tech AI
Answer from AI
In a promise chain, if a promise is rejected, the first .then is skipped, and control passes to the nearest .catch.
- The first
.catchcatches the error, logs a message, and returns a value, turning the error into a successful result. - The next
.thenreceives this value, logs it, and throws a new error. - The second
.catchcatches the new error, logs a message, but does not return anything, so the result becomesundefined. - The last
.thenreceivesundefinedand logs it.
Example:
Promise.reject('Error!')
.then(() => console.log('This then is skipped'))
.catch(err => {
console.log('Catch 1:', err); // Catch 1: Error!
return 'Another value';
})
.then(value => {
console.log('Then 2:', value); // Then 2: Another value
throw new Error('Second error');
})
.catch(err => {
console.log('Catch 2:', err.message); // Catch 2: Second error
})
.then(value => {
console.log('Then 3:', value); // Then 3: undefined
});
Thus, .catch can transform an error into a successful result, allowing the chain to continue, and if an error is thrown again, the chain becomes rejected again.