Asynchronous constructor

后端 未结 7 1917
轻奢々
轻奢々 2020-12-01 00:07

How can I best handle a situation like the following?

I have a constructor that takes a while to complete.

var Element = function Element(name){
            


        
7条回答
  •  没有蜡笔的小新
    2020-12-01 00:34

    I extract out the async portions into a fluent method. By convention I call them together.

    class FooBar {
      constructor() {
        this.foo = "foo";
      }
      
      async create() {
        this.bar = await bar();
    
        return this;
      }
    }
    
    async function bar() {
      return "bar";
    }
    
    async function main() {
      const foobar = await new FooBar().create(); // two-part constructor
      console.log(foobar.foo, foobar.bar);
    }
    
    main(); // foo bar

    I tried a static factory approach wrapping new FooBar(), e.g. FooBar.create(), but it didn't play well with inheritance. If you extend FooBar into FooBarChild, FooBarChild.create() will still return a FooBar. Whereas with my approach new FooBarChild().create() will return a FooBarChild and it's easy to setup an inheritance chain with create().

提交回复
热议问题