user4211162
user4211162

Reputation:

Angular JS function returning before http.get finishes

This block of code is returning before it gets all the info it needs I have this:

function (){
   ....
  var promise = $http.get(...)
  promise.then (...){
     //get info needed to return promise
  }
 return promise
}

It's returning before the promise.then is finished, how could I fix this?

Upvotes: 1

Views: 388

Answers (2)

Diana R
Diana R

Reputation: 1174

When you return promise, this means your request didn't finished yet. If you want to have the data, then you should have a return inside then:

function (){
   ....
  var promise = $http.get(...)
  promise.then (...){
     //get info needed to return promise
     return data;
  }
}

Or you should just have this:

function getSmth(){
   ....
  return $http.get(...)
}

and in the page were you call the above function to use the promise:

  getSmth().then (...){
     //this will be executed when the response is returned
  }

Hope this helps.

Upvotes: 1

Adam Jenkins
Adam Jenkins

Reputation: 55643

That's the way promises work - your function gets returned right away, and you attach a callback to it via .then

function someFunc() {
   return $http
     .get(...)
     .then(function() { 
        ... 
       return data; 
      });
}

someFunc()
   .then(function(data) { 
      /* to be executed after your promise.then() inside someFunc */ 
   });

Upvotes: 1

Related Questions