javascript 如何访问子函数外的变量

How to access a variable outside a subfunction in javascript

我有以下函数,它使用 GLTF loader 将模型加载到场景中(从另一个 class 导入):

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

然后我从另一个 class 调用该函数,想要将 CreateMesh 返回的 gltf.scene 网格推送到玩家数组(意味着保持玩家网格)功能。

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

我的问题是我无法在 gltfLoader.load() 函数之外访问该变量,如下例所示:

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"
    }

假设 this.gltfLoader.load 是异步的并且还没有返回承诺的变体,通过“承诺”回调式函数来处理这个问题。

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

在加载程序外登录后加载完成,请尝试这样的操作:

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

CreateMesh('./../static/player.glb', console.log) // Hooraaaa

添加到数组:

this.experience.loaderGltf.CreateMesh('./../static/player.glb', (mesh) => this.players.push(mesh))