0

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?

1 Answer 1

1

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;
            };
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.