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

前端 未结 5 1804
南笙
南笙 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

    The return value from the constructor replaces the object that the new operator just produced, so returning a promise is not a good idea. Previously, an explicit return value from the constructor was used for the singleton pattern.

    The better way in ECMAScript 2017 is to use a static methods: you have one process, which is the numerality of static.

    Which method to be run on the new object after the constructor may be known only to the class itself. To encapsulate this inside the class, you can use process.nextTick or Promise.resolve, postponing further execution allowing for listeners to be added and other things in Process.launch, the invoker of the constructor.

    Since almost all code executes inside of a Promise, errors will end up in Process.fatal

    This basic idea can be modified to fit specific encapsulation needs.

    class MyClass {
      constructor(o) {
        if (o == null) o = false
        if (o.run) Promise.resolve()
          .then(() => this.method())
          .then(o.exit).catch(o.reject)
      }
    
      async method() {}
    }
    
    class Process {
      static launch(construct) {
        return new Promise(r => r(
          new construct({run: true, exit: Process.exit, reject: Process.fatal})
        )).catch(Process.fatal)
      }
    
      static exit() {
        process.exit()
      }
    
      static fatal(e) {
        console.error(e.message)
        process.exit(1)
      }
    }
    
    Process.launch(MyClass)
    

提交回复
热议问题