AngularJS how do I execute code only after a promise is resolved? (with Restangular)

Issue

This might be a nooby question but I still haven’t been able to get my head around promises and specifically how to write code with them. (I’ve read several articles but most of them are abstract and I simply haven’t written enough to have a clear picture)
I’ve got an AngujlarJS application that gets data through a http request to another server which sends a promise at first. I’ve been able to retrieve the response from the promise and use it in my app. However because my code is poorly written. It executes other code before the promise is resolved leading to problems. It starts loading the page before it has the data.

what i have is:

var userTotals = *http request which returns a promise

$scope.data = userTotals.$object

//code that does someting with $scope.data

What i need is (I think)

var userTotals = *http request which returns a promise

$scope.data = userTotals.$object.
  beforethisresolves(function{ 
     show fancy loading icon or something })
  .whenthis resolves(function{
    //code that does someting with $scope.data
  }

however I can’t get the syntax correct.

Solution

This is what it looks like in general:

var promise = $http.post('/url');

console.log('Request started');

promise.then(function(result) {
  console.log('Success');
  console.log(result);
}, function() {
  console.log('Failure');
});

In fact, $q AngularJS documentation helped me a good deal to get my head around promises concept.

Hope this helps!

Answered By – SkyWriter

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.