Sobes.tech
Middle

Can we handle the rejected state of a Promise inside .then()?

sobes.tech AI

Answer from AI

Yes, inside the .then() method, you can handle the rejected state of a Promise by passing a second argument — an error handling function. The syntax looks like this:

promise.then(
  result => { /* handle successful result */ },
  error => { /* handle error */ }
);

However, it is more common to use the .catch() method for error handling, which is more readable and convenient for promise chains:

promise
  .then(result => { /* handle successful result */ })
  .catch(error => { /* handle error */ });

Using the second argument in .then() and .catch() is functionally equivalent, but .catch() better reflects the intention to handle errors.

Can we handle the rejected state of a Promise inside… - sobes.tech