postLoad1() and postLoad2() use the mesh from load() function, but the problem is that the model load takes so long that before the mesh is created inside the load() function, postLoad1() and postLoad(2) get called and so I get errors. I tried calling postLoad1() and postLoad(2) after a like 2-second delay and it works on one of my laptops that is fast and powerful, but on the other one, I need to increase the delay to like 5 seconds. I don’t think that’s how I am supposed to do it properly so that I don’t have to introduce a random delay/wait time.
I have also tried using promises and async-await, but nothing works.
Any suggestions or help would be much appreciated.
Yes, the 1st contact with async file loading can be quite entertaining Been through that just recently myself. Here’s how I solved this, it’s similar to a semaphore:
dataArray = [];
dataArray_ready = false;
...
...
const loader = new THREE.FileLoader();
loader.setResponseType( "arraybuffer" );
loader.load(
// resource URL
filename,
function ( data ) {
// process data and fill dataArray[] which I set up as global
fillDataArray( data );
},
// onProgress callback
function ( xhr ) {
// console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
},
// onError callback
function ( err ) {
console.error( 'An error happened' );
}
);
}
Then, in your animation loop, periodically check whether dataArray.length has become non-zero:
function render() {
if(( dataArray.length != 0 ) && !dataArray_ready ) {
...
// if so, you may safely call postLoad() stuff here
...
dataArray_ready = true;
} else {
// automatically consume frames until `dataArray` is ready.
// After that, update on OrbitControl() 'change' events only.
if ( !dataArray_ready ) requestAnimationFrame( render );
}
renderer.render( scene, camera );
}
This seems to be the most straightforward solution. I did test callback but in the wrong places.
Thanks a lot. I wish I had asked this earlier. Wasted way too much time.
I suggest try to avoid use Callback (because callback hell). Callbacks was the way people do it. The new way is async/await. And in my personal experience is the simplest way to do it.
I´m sorry. Maybe my code was no friendly (I written it 2 years ago). here are another example. if you want to learn a little more about async/await you can click here