Joel Joel - 4 months ago 17x
AngularJS Question

Using success/error/finally/catch with Promises in AngularJS

I'm using

in AngularJs, and I'm not sure on how to use the returned promise and to handle errors. I have this code:

.success(function (data) {
// Handle data
.error(function (data, status) {
// Handle HTTP error
.finally(function () {
// Execute logic independent of success/error
.catch(function (error) {
// Catch and handle exceptions from success/error/finally functions

Is this a good way to do it, or is there an easier way?


Promises are an abstraction over statements that allow us to express ourselves synchronously with asynchronous code. They represent a execution of a one time task.

They also provide exception handling, just like normal code, you can return from a promise or you can throw.

What you'd want in synchronous code is:

      var res = $http.getSync("url");
      res = someProcessingOf(res);
  } catch (e) {
      console.log("Got an error!",e);
      throw e; // rethrow to not marked as handled
  // do more stuff with res
} catch (e){
     // handle errors in processing or in error.

The promisified version is very similar:

   console.log("got an error in initial processing",e);
   throw e; // rethrow to not marked as handled, 
            // in $q it's better to `return $q.reject(e)` here
    // do more stuff
    // handle errors in processing or in error.