I finally got Angular promise error handling down but it was counter-intuitive to me. I expected errors to be handled by the failure callback but instead I had to use a catch.
I don't quite understand conceptually why the catch is executed rather than the failure callback.
What I expected:
SomeAsyncService.getData().then(function (result) {
// The call is successful.
// Code in this block throws an error.
}, function (error) {
// I expected to handle errors here.
});
What eventually worked.
SomeAsyncService.getData().then(function (result) {
// The call is successful.
// Code in this block throws an error.
}).catch(function (error) {
// Where the error is actually caught.
});
If there is a more appropriate way to handle promise errors, let me know.
This an example of a simple promise object that returns I promise to return this after 1 second! var promise = new Promise(function(resolve, reject) { setTimeout(function() { resolve('I promise to return this after 1 second!' ); }, 1000); }); promise. then(function(value) { console.
The then() method takes two callback functions as parameters and is invoked when a promise is either resolved or rejected. The catch() method takes one callback function and is invoked when an error occurs.
The second argument should be almost never be used literally in application code while also using the first. It is mostly about promise library interoperability between different implementations.
You should always use .catch
unless you specifically have some weird corner case where you need .then(succcess, fail)
.
See The .then(success, fail)
anti-pattern.
Also Q library (The one angular $q is based on) has similar section in their readme
I think you're slightly misunderstanding how promises work.
In your first code block there is only one promise object and it's SomeAsyncService.getData()
. The errorCallback is not called here because that promise is resolved.
In the second code block there are actually 2 promise objects you're working with. Note that .then()
"returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback". So what's happening is you're catching the error from the second promise returned from SomeAsyncService.getData().then(...)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With