How to access a variable outside a subfunction in javascript



I have the following function that uses a GLTF loader to load a model into the scene (imported from another class):

    CreateMesh(path){
        this.gltfLoader.load(
            path,
            (gltf) =>
            {
                this.experience.scene.add(gltf.scene)
            }
        )
    }

And I call that function from another class like this, wanting to push to the players array (meant to keep the players meshes) the gltf.scene mesh returned from the CreateMesh function.

this.players.push(this.experience.loaderGltf.CreateMesh('./../static/player.glb'))

My problem is that I cannot access that variable outside the gltfLoader.load() function as you see in the following example:

CreateMesh(path){
     let mesh = null
        this.gltfLoader.load(
            path,
            (gltf) =>
            {
                this.experience.scene.add(gltf.scene)
                mesh=gltf.scene
                console.log(mesh) // prints gltf.scene
            }
        )
      console.log(mesh) //prints "null"
    }

Answer

Assuming this.gltfLoader.load is async and doesn’t already have a promise-returning variant, handle this by “promisifying” that callback-style function.

// return a promise that resolves the result of gltfLoader.load, or "gltf"
async function loadMesh(path) {
  return new Promise(resolve => {
    this.gltfLoader.load(path, resolve);
  });
}

// place this where loadMesh is imported and players is in scope...
async createMesh() {
  let gltf = await loadMesh('some/path');
  let mesh=gltf.scene;
  this.experience.scene.add(mesh);
  this.players.push(mesh);
}
 


Source: stackoverflow