Home >Web Front-end >JS Tutorial >Should Constructor Functions Return Promises?
Constructor Functions and Promises: A Practical Approach
Consider the scenario of creating a constructor function for a blogging platform with various asynchronous operations. The question arises: is it advisable to have the constructor function return a Promise instead of the object it was intended to create?
The Pros of Returning a Promise:
The Cons of Returning a Promise:
Alternative Approaches:
Instead of returning a Promise from the constructor, consider employing one of the following strategies:
var engine = new Engine({path: '/path/to/posts'}); engine.init().then(function() { // Object is now initialized. });
Engine.create({path: '/path/to/posts'}).then(function(engine) { // Object is now initialized. });
Conclusion:
While returning a Promise from a constructor function can offer certain benefits, it is generally considered a bad practice. By following the suggested alternative approaches, you can achieve the desired functionality without disrupting the expected constructor behavior.
The above is the detailed content of Should Constructor Functions Return Promises?. For more information, please follow other related articles on the PHP Chinese website!