I'm trying to create a constructor for a blogging platform and it has many async operations going on inside. These range from grabbing the posts from directories, parsing them, sending them through template engines, etc.
So my question is, would it be unwise to have my constructor function return a promise instead of an object of the function they called new
against.
For instance:
var engine = new Engine({path: '/path/to/posts'}).then(function (eng) {
// allow user to interact with the newly created engine object inside 'then'
engine.showPostsOnOnePage();
});
Now, the user may also not supply a supplement Promise chain link:
var engine = new Engine({path: '/path/to/posts'});
// ERROR
// engine will not be available as an Engine object here
This could pose a problem as the user may be confused why engine
is not available after construction.
The reason to use a Promise in the constructor makes sense. I want the entire blog to be functioning after the construction phase. However, it seems like a smell almost to not have access to the object immediately after calling new
.
I have debated using something along the lines of engine.start().then()
or engine.init()
which would return the Promise instead. But those also seem smelly.
Edit: This is in a Node.js project.
.init()
method that can then return the promise. Then you separate out instance data in the object and construction of that object from the async initialization operation. The same issue arises when you have all sorts of different errors (which the caller wants to handle differently) that can occur in the initialization of the object. Much better to return the object from the constructor and then use.init()
to return other things. – Remembrancer