I have the following code. And it works as expected without throwing a unhandled rejection error.
p = new Promise (fulfill, reject) ->
reject new Error 'some error'
p.catch (error) ->
console.log error
Now, the second code example does throw an unhandled rejection error. Can someone explain to me why this is happening when im clearly handling the error.
p = new Promise (fulfill, reject) ->
reject new Error 'some error'
p.then ->
console.log 'ok'
p.catch (error) ->
console.log error
Btw. I'm testing in chrome and bluebird v3.4.7
When you chain Promises, each chain is treated as new instance of Promise.
catch()
is similar to then()
except you only provide handler on rejection case.
So in your example 1: Your catch()
is for handling the rejection of the original promises where the Error was created.
In example 2: It is saying, when first promise is resolve please move on to 2nd Promise where you provide then handler on success and failure. The catch()
that you have there is for handling error in the function within the then()
, not the one raised by the 1st Promise
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch for more info on how catch works
Per error management configuration Bluebird throws an error if there is no catch handler registered when a promise is rejected, without waiting to see if one is added in the future. Note that checking for a rejection handler should be done asynchronously to the thread which set up the promise chain. As they say, "some programming patterns will result in false positives". Yes really?
On the other hand, uncaught exception errors are not part of the ES6 standard and implementations handle them in different ways: Firefox waits, or used to wait, until GC time whereas Chrome times out (or used to time out) with a "possible uncaught promise rejection" error.
Consult Blue bird documentation for possible solutions for Bluebird promises which error before attaching a handler.
But since both examples synchronously attach a reject handler for promise p
, the reason for the exception appears to lie elsewhere.
With thanks to @DJ 's answer but with a different interpretation. In the second example, then
returns a promise which is rejected if p
is rejected, and does not have a rejection handler. The promise returned by .then
is likely to be the one throwing the error.
来源:https://stackoverflow.com/questions/41817407/unhandled-rejection-error-bluebird