Is it bad practice to have a constructor function return a Promise?

前端 未结 5 1907
南笙
南笙 2020-11-21 06:52

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 t

5条回答
  •  耶瑟儿~
    2020-11-21 07:48

    I encountered the same problem and came up with this simple solution.

    Instead of returning a Promise from the constructor, put it in this.initialization property, like this:

    function Engine(path) {
      var engine = this
      engine.initialization = Promise.resolve()
        .then(function () {
          return doSomethingAsync(path)
        })
        .then(function (result) {
          engine.resultOfAsyncOp = result
        })
    }
    

    Then, wrap every method in a callback that runs after the initialization, like that:

    Engine.prototype.showPostsOnPage = function () {
      return this.initialization.then(function () {
        // actual body of the method
      })
    }
    

    How it looks from the API consumer perspective:

    engine = new Engine({path: '/path/to/posts'})
    engine.showPostsOnPage()
    

    This works because you can register multiple callbacks to a promise and they run either after it resolves or, if it's already resolved, at the time of attaching the callback.

    This is how mongoskin works, except it doesn't actually use promises.


    Edit: Since I wrote that reply I've fallen in love with ES6/7 syntax so there's another example using that. You can use it today with babel.

    class Engine {
    
      constructor(path) {
        this._initialized = this._initialize()
      }
    
      async _initialize() {
        // actual async constructor logic
      }
    
      async showPostsOnPage() {
        await this._initialized
        // actual body of the method
      }
    
    }
    

    Edit: You can use this pattern natively with node 7 and --harmony flag!

提交回复
热议问题