Middle
Is it possible to handle the rejected state of a promise inside then? What is the difference between handling reject in the second then callback and in catch?
sobes.tech AI
Answer from AI
Yes, inside then you can handle the rejected state by passing a second callback to then:
promise.then(
result => { /* handle successful result */ },
error => { /* handle error */ }
);
The difference between handling reject in the second then callback and in catch:
- The second then callback only handles errors that occur in the original promise.
- catch catches errors that occur both in the original promise and in any previous then, if they were not handled.
Thus, catch is more convenient for centralized error handling, while the second then callback is for local handling of errors of a specific promise.