texdade
texdade

Reputation: 102

How to fix undefined promise error in AngularJS

I'm trying to create a promise in AngularJS: basically I need to call the function session.state() that makes an http request and then returns some data. I can't access the data right away because they are still undefined and not yet returned, so I tried to build a promise.

This is what I tried so far:

This is where I call session.state():

session.state()
  .then(function(data){
  if (data['state']) {
    self.plan = data['plan'];
    self.pool_interface = data['pool_interface'];
  }
  callback(data['state']);
});

and here is session.state() itself:

self.state = function() {
  $http.get(self.baseUrl + 'api/session/state')
  .then(function(response) {
    var dfd = $q.defer();
    dfd.resolve(response.data);
    return dfd.promise;
  });
};

The two pieces of code are placed in separate services.

So far I'm only getting the "Error: session.state(...) is undefined" error from the browser console. What am I doing wrong?

Upvotes: 0

Views: 77

Answers (1)

Wasef Anabtawi
Wasef Anabtawi

Reputation: 1021

you should define the defer and return it outside your async operation, like this:


           self.state = function() {
              var dfd = $q.defer();
              $http.get(self.baseUrl + 'api/session/state')
              .then(function(response) {

                dfd.resolve(response.data);

              });
               return dfd.promise;
            };

Upvotes: 1

Related Questions