异步问题与OBJLoader - 等待XHR完成加载 [英] Asynchronous issue with OBJLoader - wait for XHR to finish loading

查看:572
本文介绍了异步问题与OBJLoader - 等待XHR完成加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你怎么能做出OBJLoader简单地返回对象,而不是将其添加到现场?我打了一个同步问题在我的code没有等待XHR请求结束,引发错误。

How can you make OBJLoader simply return the object rather than add it to the scene? I hit a synchronization problem where my code does not wait for the XHR request to finish, throwing errors.

以下示例说明了这个问题:

The following example shows the problem:

var loader = new THREE.OBJLoader();

// return a mesh from an obj file   
function createObject( objFile, objName ) {
    object3d = loader.load( objFile , function ( object ) {
        object.name = objName;            
        console.log(object);
        return object;
    })
    return object3d;
}

car = createObject('path/to/car.obj', 'abc123');
car.position.y = 10;

这生成控制台以下内容:

This generates the following in console:

1. Uncaught TypeError: Cannot set property 'position' of undefined test.html:171
2. XHR finished loading: GET "path/to/car.obj". Three.js:11377
3. THREE.Object3D {id: 7, uuid: "9E8DC838-E68B-4FCA-A6AD-863D5D06D31F", name: "abc123", parent: undefined, children: Array[1]…}

因此​​,(1)存在错误,因为car.position.x发生而XHR请求正在进行中,该对象为null。我的code不等待。但(2)和(3)表明,不久后,负载请求确实成功完成。

So error (1) exists because 'car.position.x' happens while the XHR request is in progress and the object is null. My code doesn't wait. But (2) and (3) show that shortly after, load request does complete successfully.

任何想法,我怎样才能使这项工作?我怎样才能让CREATEOBJECT()等到XHR请求继续之前完成?还是这只是一般测序事情坏的方式?

Any ideas how I can make this work? How can I make createObject() wait until the XHR request is finished before continuing? Or is this generally just a bad way to sequence things?

推荐答案

您可以创建你的方法内部的容器和对象添加到容器一旦加载。

You can create a "container" inside your method and add the object to that container once it loads.

var loader = new THREE.OBJLoader();

// return a mesh from an obj file   
function createObject( objFile, objName ) {
    var container = new THREE.Object3D();
    loader.load( objFile , function ( object ) {
        object.name = objName;
        container.add( object );
    })
    return container;
}

car = createObject('path/to/car.obj', 'abc123');
car.position.y = 10;

这篇关于异步问题与OBJLoader - 等待XHR完成加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆