2

I am new to javascript, I need some help understanding how promises(using bluebird) should be used. Below is my code and I want the constructor to initialize a property after property is resolved.

var getCookie = function(object, someParams) {
   return connect(someParams)
   .then(function(response){
      self.cookie = response.cookie;//this should be done as part of object initialization.
      done();
    });
}

var app = function(){
  var self = this;
  getCookie(self);
  //how to make sure that return happens after promise is resolved?
  return self;
}
learningtocode
  • 755
  • 2
  • 13
  • 27

1 Answers1

6

how to make sure that return happens after promise is resolved?

You can't. The app function will return before the promise is resolved. That is even guaranteed by JavaScript.

How to call promise object in constructor to set a property

You don't.

Instead you have something like a factory method that creates a new instance of the class, and returns a promise that resolves to the instance.

Example:

function getCookie(someParams) {
 return connect(someParams)
   .then(function(response){
     return response.cookie;
   });
}

function App() {}

function getApp() {
  var app = new App();
  return getCookie(params)
    .then(function (cookie) {
      app.cookie = cookie;
      return app;
    });
}

// Usage

getApp().then(function(app) {
  // use app
});

One uses promises for asynchronous processes. Constructor functions are synchronous. While you can use promises in constructors, the returned instance won't be fully initialized until the promise is resolved. But your code would never know when that is.

That's why having a factory method that returns a promise that resolves to the class instance if the more reliable way.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • I tried this approach and whats happening is that the app is being returned without the cookie being set. It gets set after sometime..how do we make sure that it does not return before completing the promise? Do we have to add a promise monitor? I understand that this sounds more like synchronous programming, but the api I use only returns promises – learningtocode Oct 03 '16 at 23:35
  • Then you are not doing what I am suggesting in my answer. Here is an implementation with a fake `connect` implementation: https://jsfiddle.net/yqu5szLb/ . "*Do we have to add a promise monitor?"* No. Promises already solve that problem. The callback passed to `getApp().then(...)` is only executed *after* `app.cookie = cookie;` happened. – Felix Kling Oct 03 '16 at 23:40