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

前端 未结 5 1826
南笙
南笙 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:28

    To avoid the separation of concerns, use a factory to create the object.

    class Engine {
        constructor(data) {
            this.data = data;
        }
    
        static makeEngine(pathToData) {
            return new Promise((resolve, reject) => {
                getData(pathToData).then(data => {
                  resolve(new Engine(data))
                }).catch(reject);
            });
        }
    }
    

提交回复
热议问题