angularjsangular-promiseangularjs-http

chaining http.get promises with angular service


Is this a bad way to do this? I'm basically chaining promises, where each successful return from server, launches a new http.get() for more information BUT NOT when it errors. No more http.get()s if it causes an errorCallback!

$http.get(...).then(function() {
  $http.get(...).then(function(){ 
      $http.get(...).then(function(){}, function(){}), 
   function(){}); }, 
mainErrorCallback);

Would it make a difference if it was instead of "$http.get()" it does "ViewsService.loadViews()" inside the

$http.get(...).then( function() { ViewsService.loadViews(); }, function(){ console.log("error"); }). 

EDIT: Here's what I mean, synchronously.. it seems like it works, but code needs cleanup/efficency to look a little neater:

http://jsfiddle.net/4n9fao9q/6/

(with delayed http requests): http://jsfiddle.net/4n9fao9q/26


Solution

  • $http.get(...).then((res) => {
      //res has data from first http
      return $http.get(...);
    }).then((res) => {
      //res has data from second http
      return $http.get(...);
    }).then((res) => {
      //res has data from third http
    }).catch((err) => {
      //exploded
    });
    

    I think is cleaner. You can replace $http.get with whatever function returns a promise. If ViewsService.loadViews() returns a promise, you can use it.

    As asked in the comments.

    ...
    ViewsService.loadViews = function() {
      //returns a promise
      return $http.get(...);
    }
    
    OR
    
    ViewsService.loadViews = function() {
      return new Promise((resolve, reject) => {
        $http.get(...).then((result) => {
          //whatever
          return resolve();
        })
      })
      return $http.get(...);
    }
    

    With any of this options for loadViews you can do ViewsService.loadViers.then(etc)