Most simple way to wait loading in GLTF loader

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);
});


8 Likes