[英]How can I run a callback when I know all asynchronous calls have been completed?
I am making an application using Three.js, to create a textual geometry and add it to the scene, I pass a function.我正在使用 Three.js 创建一个应用程序,以创建文本几何并将其添加到场景中,我传递了 function。 However, I can do this several times and I have created a method that iterates over all meshes in the scene and performs some visual changes.
但是,我可以多次执行此操作,并且我创建了一个迭代场景中所有网格并执行一些视觉更改的方法。 My Question is, how can I know when all async calls have completed and I know all meshes have been added to the scene, such that when I call my method and iterate over all meshes in the scene, all meshes have been successfully added?
我的问题是,我怎么知道所有异步调用何时完成并且我知道所有网格都已添加到场景中,这样当我调用我的方法并迭代场景中的所有网格时,所有网格都已成功添加?
eg例如
/* Create the scene Text */
let loader = new THREE.FontLoader();
loader.load('fonts/helvetiker_regular.typeface.json', font => {
/* Create the geometry */
let geometry_text = new THREE.TextGeometry("example text");
/* Currently using basic material because I do not have a light, Phong will be black */
let material_text = new THREE.MeshBasicMaterial();
let textMesh = new THREE.Mesh(geometry_text, material_text);
scene.add(textMesh); // <---------- Adds the mesh to the scene
});
fade_meshes_into_scene(); // <------- iterates over all meshes in scene.
In this example, It will not work since fade_meshes_into_scene
iterates over all meshes in the scene and in this case the scene will have no meshes because it's called before scene.add(textMesh)
is called.在这个例子中,它不起作用,因为
fade_meshes_into_scene
迭代场景中的所有网格,在这种情况下,场景将没有网格,因为它是在调用scene.add(textMesh)
之前调用的。 However, I can move it inside the async call when I only do it once, but will fail to work when I add multiple text and different async calls.但是,当我只执行一次时,我可以将它移动到异步调用中,但是当我添加多个文本和不同的异步调用时将无法工作。
How can I know when I have added all of my meshes so I know when to call fade_meshes_into_scene
?我如何知道何时添加了所有网格,以便知道何时调用
fade_meshes_into_scene
?
I recommend you turn your font loading into Promises.我建议您将字体加载转换为 Promises。 You can then use
Promise.all
to guarantee that all promises in an array have resolved before executing the function you pass to then
..然后,您可以使用
Promise.all
来保证数组中的所有承诺在执行您传递给then
的 function 之前都已解决。
const loadFont = fontPath => {
return new Promise(res => {
loader.load(fontPath, font => {
// do loading things
scene.add(textMesh);
res();
});
});
}
const font1 = loadFont('font-path-1.json'); // Promise for first font
const font2 = loadFont('font-path-2.json'); // Promise for second font
Promise.all([font1, font2]).then(() => {
fade_meshes_into_scene();
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.