Ivan
Ivan

Reputation: 16908

Angular chain promise immediately after the first

I have two factories : getPosition gets current location, geoCoding uses google reverse geocoding to get the city name. Both of them use $q.defer() and both of them write the data received to local storage. I want to chain them on page load. So the position should write the current position to local storage and then geocoding should immediately decode it. I tried to chain them like that:

   getPosition.get().then(function(geoInfo){
    $scope.$storage.geoInfo = geoInfo;
    return geoCoding.get().then(function(city){
      $scope.$storage.city = city;
      $scope.city = $scope.$storage.city;
    },function(reason){
      alert("Geocoding error: " + reason);
    })
  }, function(reason){
    alert("Location error: " + reason);
  });

But this way i only get the position on initial page load, and i get the city on page refresh. I've read the documentation and searched stackoverflow, but i'm still missing something. How to chain the calls so that both of them are received at page load?

Upvotes: 1

Views: 61

Answers (2)

Ivan
Ivan

Reputation: 16908

The problem resolved when I used the data received from the first call directly, without writing to local storage. I don't know why it works only like that, but anyway, it works.

Upvotes: 1

Matt Herbstritt
Matt Herbstritt

Reputation: 4862

Not tested this but maybe you could try doing something like this:

getPosition
    .get()
    .then(function(geoInfo){
      $scope.$storage.geoInfo = geoInfo;
      return geoCoding.get();
    })
    .then(function(city){
      $scope.$storage.city  = city;
      $scope.city           = $scope.$storage.city;
    })
    .catch(function(error){
      alert("Error: " + error);
    });

Not sure if you can do this with $q but I've used this with bluebird. It seems counter to the main benefit of promises to be adding more then() calls within then() calls. It's just the same as the callback hell promises were meant to prevent. So I'd be surprised if you can't chain all your promises like above.

Upvotes: 2

Related Questions