Mischa
Mischa

Reputation: 2139

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

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.

Upvotes: 0

Views: 5128

Answers (3)

Daniel Pacak
Daniel Pacak

Reputation: 1439

Assuming that you're using Bootstrap modal you can do the following:

function openModalWithProgressIndicator(deferred) {
  const progressModal = $uibModal.open({
    templateUrl: 'templates/modals/progress.html',
    backdrop: 'static'
  });
  return deferred.then(function (value) {
    return value;
  }).finally(function () {
    progressModal.close();
  });
}

The deferred argument passed to this function is a promise. That said you can now do the following:

const deferred = $http.post('http://somewhere/data', {foo: 'bar'});

openModalWithProgressIndicator(deferred)
  .then(function (httpResponse) {
    // do sth with httpResponse.data
  }).catch(function (error) {
    // do sth with error
  });

So the main point to note is the finally callback that's always executed.

Upvotes: 0

tommy
tommy

Reputation: 1026

var successCallback = function(){//...};
var errorCallback = function(){//...};

$http
 .post('url', data)
 .success(successCallback)
 .error(errorCallback);

//OR

$http
 .post('url', data)
 .then(successCallback, errorCallback);

Upvotes: 0

SkyWriter
SkyWriter

Reputation: 1479

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!

Upvotes: 2

Related Questions