learningtocode learningtocode - 2 months ago 7
Javascript Question

How to call promise object in constructor to set a property

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;
}

Answer

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(someParam) {
 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.

Comments