Joel Joel - 1 year ago 92
AngularJS Question

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

I'm using

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

$http.get(url)
.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?

Answer Source

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:

try{
  try{
      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:

$http.get("url").
then(someProcessingOf).
catch(function(e){
   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
}).then(function(res){
    // do more stuff
}).catch(function(e){
    // handle errors in processing or in error.
});