【问题标题】:How to access a variable outside a subfunction in javascript如何在javascript中访问子函数外部的变量
【发布时间】:2021-11-27 02:11:12
【问题描述】:

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

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

我从另一个类似的类中调用该函数,希望将 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"
    }

【问题讨论】:

  • 它看起来像一个异步函数。网格在日志点未定义,因为初始化它的函数尚未运行。
  • 这是同步和异步代码执行的问题。尝试在您的第二个 console.log 周围使用 setTimeout 并查看您的问题。为什么需要在加载后立即访问mesh

标签: javascript three.js


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    在加载程序之外登录后加载完成,因此请尝试以下操作:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-01
      • 1970-01-01
      • 2020-10-30
      • 1970-01-01
      • 2022-12-02
      • 1970-01-01
      • 2021-01-04
      • 1970-01-01
      相关资源
      最近更新 更多