While Promise is definitely useful feature, I still see some people confused about the semantic of promise resolution and error handling. Here's a few examples that I've seen people trip over so far.
Once promise is resolved, the value stays the same.
If you want to use the return value from the next promise handler, you have to assign them to another variable. But the original value stays the same.
Browsers and node.js will warn you if you have any missing rejection handler. This is not a bug, you should always handle your rejected promise. You can do that using
.catch. Please keep in mind that these two methods are different, but can be similar in some cases.
onRejected handler is passed as a second argument in
If you don't put
onRejected handler, the behavior will be similar to this:
Which will propagate the error through the promise handler and causing uncaught rejection error, unless you handle the error in the next promise handler.
You can also use
.catch method to handle error from previous promise:
Now, you might think that those two method behave the same way, but they don't.
Consider this example:
In the first case,
errorCallback only handles rejection (or error) from
successCallback throws an error,
errorCallback won't catch them and you will get uncaught rejection error. You still need to put
.catch if you want to handle error coming from
In the second case,
errorCallback will catch error from Promise resolved by
successCallback. Because the
.then handler only include 1 argument (only handle fulfilled state), if
samplePromise is rejected, the error will propagate through and will be handled by
By knowing this you can use
.catch to act as catch all error:
.catch handler will handle error / rejection in
.then handler only handle error in the exact previous promise, while
.catch will handle error in all previous promises.
When you specify
onRejected handler (or
.catch) the return value from the callback will be used as fulfilled state for the next promise
Even when you don't specify any return value, when the rejected promise is handled by
.catch, it will still be resolved to
Next time you handle an error in Promise, give meaningful return value or make sure it's the last error handler (so there's no more promise handler) to prevent unnecessary surprise.