Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Angular, what's the conceptual difference between the error and catch functions for promises?

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.

like image 270
Jason Avatar asked Oct 25 '13 17:10

Jason


People also ask

How do you use promises in angular 8?

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.

What is .then in angular?

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.


2 Answers

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

like image 70
Esailija Avatar answered Sep 19 '22 08:09

Esailija


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(...).

like image 43
Roy Daniels Avatar answered Sep 20 '22 08:09

Roy Daniels