Using promises with $http
HTTP requests are the quintessential variable latency operations that demand a promise construct. Since it would appear that developers are stuck with the uncertainty stemming from TCP/IP for the foreseeable future, it behooves you to architect your applications to account for this.
How to do it…
The $http
service methods return an AngularJS promise with some extra methods, success()
and error()
. These extra methods will return the same promise returned by the $http
service, as opposed to .then()
, which returns a new promise. This allows you to chain the methods as $http().success().then()
and have the .success()
and .then()
promises attempt to resolve simultaneously.
The following two implementations are more or less identical, as everything is being chained upon the $http
promise:
// Implementation #1 // $http.get() returns a promise $http.get('/myUrl') // .success() is an alias for the resolved handler .success(function(data, status, headers, config, statusText)...