Home > database >  Correct return of Promise results
Correct return of Promise results

Time:11-03

I would like to load textures in a class and only after all textures have been loaded may the class be called. Loading the textures works but i don't know how and where to call the class at the right place so that it is returned to the main class. I have reduced the code to the absolute neccessary to show my problem

class Environment { 
    constructor(params) {
                        
        this._Init(params);         
    }

    static init(params) { 
            
        const getTextures = () => new Promise((resolve, reject)=>{ 
            const manager = new THREE.LoadingManager(()=>resolve(textures)); 
            const loader = new THREE.TextureLoader(manager); 
            const textures = [ 
                './resources/simplex-noise.png',
                //next texture,
                //next texture,
                //next texture,
            ].map(filename=>loader.load(filename)); 
        }); 
        getTextures().then(tex => {
            return new Environment({params, tex}); //here something is wrong.
            //I need "new Environment({params, tex});" as return for "static init"
        });

        //return new Environment(params);  //this is working but here i have no preloaded tex
    } 



    _Init(params) {
        this.params_ = params;

        //....          
    
    }
}



class Main {
    constructor(){
        this._Initialize();
    }

    _Initialize() {   
        //...
        this.OnAppStarted_();
        //...
    }

    OnAppStarted_() {
        this.LoadControllers_();
    }


    LoadControllers_() {
  
        this.obj = Environment.init({
            //params
        });
        
        //...
        
    }
    
    //...
    
}

CodePudding user response:

class Environment { 
constructor(params) {
                    
    this._Init(params);         
}

static init(params) { 
        
    // ...
    // add return
    return getTextures().then(tex => {
        return new Environment({params, tex}); //here something is wrong.
        
    });
} 

}

  • Related