Asynchronous constructor

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

    I have developed an async constructor:

    function Myclass(){
     return (async () => {
         ... code here ...
         return this;
     })();
    }
    
    (async function() { 
     let s=await new Myclass();
     console.log("s",s)
    })();
    
    • async returns a promise
    • arrow functions pass 'this' as is
    • it is possible to return something else when doing new (you still get a new empty object in this variable. if you call the function without new. you get the original this. like maybe window or global or its holding object).
    • it is possible to return the return value of called async function using await.
    • to use await in normal code, need to wrap the calls with an async anonymous function, that is called instantly. (the called function returns promise and code continues)

    my 1st iteration was:

    maybe just add a callback

    call an anonymous async function, then call the callback.

    function Myclass(cb){
     var asynccode=(async () => { 
         await this.something1();
         console.log(this.result)
     })();
    
     if(cb)
        asynccode.then(cb.bind(this))
    }
    

    my 2nd iteration was:

    let's try with a promise instead of a callback. I thought to myself: strange a promise returning a promise, and it worked. .. so the next version is just a promise.

    function Myclass(){
     this.result=false;
     var asynccode=(async () => {
         await new Promise (resolve => setTimeout (()=>{this.result="ok";resolve()}, 1000))
         console.log(this.result)
         return this;
     })();
     return asynccode;
    }
    
    
    (async function() { 
     let s=await new Myclass();
     console.log("s",s)
    })();
    

    callback-based for old javascript

    function Myclass(cb){
     var that=this;
     var cb_wrap=function(data){that.data=data;cb(that)}
     getdata(cb_wrap)
    }
    
    new Myclass(function(s){
    
    });
    

提交回复
热议问题