简体   繁体   中英

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?

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 */ 
   });

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM