我結束了持續的承諾路線:包裹在JavaScript中的TextureLoader.load()
調用內置的承諾,返回名爲constructor Promise
:
var loadTexture_promise = (texture_path, texture_loader) => {
var texture_promise;
if ( loadTexture_promise.texturePromises_cache[texture_path] !== undefined) {
return loadTexture_promise.texturePromises_cache[texture_path]
}
texture_promise = new Promise(
function(resolve, reject)
{
texture_loader.load(
texture_path,
function (texture) {
// Success callback of TextureLoader
// We're done, so tell the promise it is complete
resolve(texture);
},
function (XmlHttpRequest_instance) {
// Progress callback of TextureLoader
},
function (unknown_parameter) {
// Failure callback of TextureLoader
// Reject the promise with the failure
reject(new Error('Could not load texture ' + texture_path));
}
);
}
);
// add texture_promise to cache:
loadTexture_promise.texturePromises_cache[texture_path] = texture_promise;
return texture_promise;
};
// establish cache object on the loadTexture_promise function:
loadTexture_promise.texturePromises_cache = [];
然後我有一個lambertMesher
功能,我的幾何供應商可撥打:
function lambertMesher (aGeometry, aTexture_promise, doubleSided, debug) {
var aMesh_promise = aTexture_promise.then(
(resolved_texture) =>
{
var material, mesh;
if (debug) {
console.log("resolved_texture: ", resolved_texture);
console.log("aGeometry: ", aGeometry);
}
resolved_texture.minFilter = THREE.NearestFilter;
if (doubleSided) {
material = new THREE.MeshLambertMaterial({ map: resolved_texture, side: THREE.DoubleSide });
} else {
material = new THREE.MeshLambertMaterial({ map: resolved_texture, emissive: 0xffffff });
}
mesh = new THREE.Mesh(aGeometry, material);
if (debug) {
console.log("mesh: ", mesh);
}
return mesh
},
(reason_of_textureLoading_failure) =>
{
console.log("meshing failed. Also: " + reason_of_textureLoading_failure)
}
);
return aMesh_promise
}
最後,我這是怎麼叫我lambertMesher
:
var myPlateGeom = new THREE.PlateGeometry(myPlatePolygonSet, true);
var myPlateMesh_promise = utils_meshers.lambertMesher(myPlateGeom, myRobinieTexture_promise, true, false);
,然後,終於終於,我在我的網添加到我的場景是這樣的:
myPlateMesh_promise.then(
(myPlateMesh) => { myScene.add(myPlateMesh) },
(reason) => console.log("failed to add myPlateMesh. Also: " + reason)
);
因爲你需要等待加載紋理,承諾是迄今爲止在這裏最合適的。關於諾言的好處是你可以繼續調用'.then()',這會讓你的代碼更加乾淨。這聽起來像你不需要承諾的幫助,但我已經回答了一個類似的問題之前:http://stackoverflow.com/questions/33283386/is-there-a-way-to-wait-for-三textureloader負載到結束/ 33292152#33292152 – Leeft