0

Main code:

var u = new User():

UserController.show(u);

user model class:

function User(id) {

   var data;

   fetchData(id).then(function(data){
      var data = response;
   }) ;
   // **here need to wait when promise is finished**

   // Return user data object from server via ajax request
   function fetchData(id) {
      return new Promise(....)
   }
}

The problem is the that when called UserController.show(u); user data is not initialized, beacause function fetchData(id) is not finished.

How to wait when promise is finished after call fetchData?

Stanislav
  • 923
  • 1
  • 11
  • 28
  • Take a look at the [example](https://developers.google.com/web/fundamentals/getting-started/primers/promises) – MaxZoom Feb 16 '17 at 15:19
  • 3
    You need to expose the promise to the outside so outside code can wait for it; or perhaps you rather want a factory which returns a promise which resolves to a `User` object, instead of doing that while instantiating the object: `createUser(id).then(user => UserController.show(user))`. – deceze Feb 16 '17 at 15:21
  • See http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Felix Kling Feb 16 '17 at 15:24
  • If you really want to do that in the constuctor, then store the promise resulting from the fetch in a property, and access it with `u.data.then(...)`. –  Feb 16 '17 at 16:00

0 Answers0