Most simple way to wait loading in GLTF loader

As I understand, GLTF loader is working asynchronous. What if I need to wait loading and then apply some code

var loader = new THREE.GLTFLoader();
var urlgltf = decodeURIComponent(container.dataset.url);
loader.load( urlgltf, function ( gltf ) {
       model = gltf.scene;
       scene.add( model );
}
model.dosomething();

I want to add something to model, but GLTF and new actions will be optional in my scene, so, I can’t add code inside load() function, I need it outside GLTF loader. Is any method to wait loading of GLTF loader, get access to all variables like model in example above?

1 Like

The most simple way (at least in animation loops) is:

if ( model ) {

    model.dosomething();

}

yes, this is what I use now. But it’s working in animation loop, but I need something outside animation. For example, I want to add lights. And these lights must point to GLtF model if it’s existing and other object if model is not existing

Currently, I forced to build two functions - one for GLTF loader and second for context which is outside loader. It’s bad that we don’t have option to check if loader finished it’s job

You can use async/await. First, you need to convert the loader to return a promise:

Note: this is now build in for all loaders, use .loadAsync instead of load.

import { GLTFLoader } from '../../../vendor/three/examples/jsm/loaders/GLTFLoader.js';

const loader = new GLTFLoader();

// this utility function allows you to use any three.js
// loader with promises and async/await
function modelLoader(url) {
  return new Promise((resolve, reject) => {
    loader.load(url, data=> resolve(data), null, reject);
  });
}

Then use it like this:

async function main() {
   const gltfData = await modelLoader(URL),

   model = gltf.scene;
   scene.add(model);

   dosomething(model);
}

main().catch(error => {
  console.error(error);
});


7 Likes

Thank you. I also found some cool function to convert anything to Promise based

https://blackthread.io/blog/promisifying-threejs-loaders/

1 Like

That’s my old site :grin:. I think the solution I shared here is better.

3 Likes