Promises
Introduction
Starting with v3.2, we introduced (without breaking backward compatibility, of course) a new pattern: promises. To learn more about promises, please read this great MDN web documentation.
In a nutshell, the basic idea is to rely on promises instead of dealing with pyramids of callbacks that are intricate and hard to maintain. For portability, Babylon.js provides a custom polyfill for browsers where promises are not supported, so you can use them without worrying about support.
Examples
Basic usage
import { LoadAssetContainerAsync } from "@babylonjs/core/Loading/sceneLoader";LoadAssetContainerAsync("https://playground.babylonjs.com/scenes/", "skull.babylon", scene).then(function (container) { container.addAllToScene();});Chaining multiple promises together
import { AppendSceneAsync } from "@babylonjs/core/Loading/sceneLoader";import { Scene } from "@babylonjs/core/scene";const scene = new Scene(engine);const xrPromise = scene.createDefaultXRExperienceAsync();xrPromise .then((xrExperience) => { return AppendSceneAsync("https://playground.babylonjs.com/scenes/", "skull.babylon", scene);}) .then(function () { // xr resolved, skull added to the scene});Using async/await with promises
Note: This is not supported in all browsers.
import { AppendSceneAsync } from "@babylonjs/core/Loading/sceneLoader";import { Scene } from "@babylonjs/core/scene";const main = async function () { const scene = new Scene(engine); const xrPromise = await scene.createDefaultXRExperienceAsync(); return AppendSceneAsync("https://playground.babylonjs.com/scenes/", "skull.babylon", scene);};Loading two glTF assets in parallel
import { ImportMeshAsync } from "@babylonjs/core/Loading/sceneLoader";import { Scene } from "@babylonjs/core/scene";const scene = new Scene(engine);const baseUrl = "https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/";Promise.all([ ImportMeshAsync(baseUrl + "BoomBox/glTF/BoomBox.gltf", scene).then(function (result) { result.meshes[0].position.x = 0.01; }), ImportMeshAsync(baseUrl + "Avocado/glTF/Avocado.gltf", scene).then(function (result) { result.meshes[0].position.x = -0.01; result.meshes[0].position.y = -0.01; result.meshes[0].scaling.scaleInPlace(0.25); }),]).then(() => { scene.createDefaultCameraOrLight(true, true, true); scene.activeCamera.alpha += Math.PI;});