I have presented a simple example to illustrate what my problem is. in functions it's easy to use await async to make sure textures are loaded before proceeding with the program. if I want to work with classes because of the cleanliness of the program, I have no idea how I can do this so that the constructor waits until the texture is loaded before the subsequent function is called.
//in my three.js init function
var sphereObject = new Sphere(100, texture);
var sphere = this.sphereObject.sphere;
scene.add(sphere);
//------------------------
class Sphere{
constructor(radius, preloadedtex){
//this.material = this.doSomething(preloadedtex); this work fine
const loader = new THREE.TextureLoader();
loader.load("grass.png", function(texture){
this.material = this.doSomething(texture);
});
const geometry = new THREE.SphereGeometry( radius, 128, 64 );
this.sphere = new THREE.Mesh( geometry, this.material);
}
doSomething(texture){
//further operations with the texture before the function returns a material
return material;
}
}
TextureLoader has an onLoad callback as the second argument of .load(). This is taken directly from the docs:
const loader = new THREE.TextureLoader();
// load a resource
loader.load(
// resource URL
'textures/land_ocean_ice_cloud_2048.jpg',
// onLoad callback
function ( texture ) {
// in this example we create the material when the texture is loaded
const material = new THREE.MeshBasicMaterial( {
map: texture
} );
},
// onProgress callback currently not supported
undefined,
// onError callback
function ( err ) {
console.error( 'An error happened.' );
}
);