Asynchronous constructor

后端 未结 7 1918
轻奢々
轻奢々 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:24

    Update 2: Here is an updated example using an asynchronous factory method. N.B. this requires Node 8 or Babel if run in a browser.

    class Element {
        constructor(nucleus){
            this.nucleus = nucleus;
        }
    
        static async createElement(){
            const nucleus = await this.loadNucleus();
            return new Element(nucleus);
        }
    
        static async loadNucleus(){
            // do something async here and return it
            return 10;
        }
    }
    
    async function main(){
        const element = await Element.createElement();
        // use your element
    }
    
    main();
    

    Update: The code below got upvoted a couple of times. However I find this approach using a static method much better: https://stackoverflow.com/a/24686979/2124586

    ES6 version using promises

    class Element{
        constructor(){
            this.some_property = 5;
            this.nucleus;
    
            return new Promise((resolve) => {
                this.load_nucleus().then((nucleus) => {
                    this.nucleus = nucleus;
                    resolve(this);
                });
            });
        }
    
        load_nucleus(){
            return new Promise((resolve) => {
                setTimeout(() => resolve(10), 1000)
            });
        }
    }
    
    //Usage
    new Element().then(function(instance){
        // do stuff with your instance
    });
    

提交回复
热议问题