How To

Use Promises

How To Use Promises


Starting with v3.2, we introduced (without breaking backward compatibility of course) a new pattern: the 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 having to deal with pyramids of callbacks intricated in a non easy to maintain way. Regarding portability, Babylon.js provides a custom polyfill for browsers where promises are not supported so you can blindly use them.


Basic usage

BABYLON.SceneLoader.LoadAssetContainerAsync("", "skull.babylon", scene).then(function (container) {

Demo -

Chaining multiple promises together

var scene = new BABYLON.Scene(engine);
var helper = scene.createDefaultVRExperience();
helper.webVRCamera.useStandingMatrixAsync().then(function (supported) {
    return BABYLON.SceneLoader.AppendAsync("", "skull.babylon", scene);
}).then(function () {
    //added to scene

Using async/await with promises

Note: This is not supported in all browsers

var main = async function () {
    var scene = new BABYLON.Scene(engine);
    var helper = scene.createDefaultVRExperience();
    var supported = await helper.webVRCamera.useStandingMatrixAsync();
    await BABYLON.SceneLoader.AppendAsync("", "skull.babylon", scene);

Loading two glTF assets in parallel

var scene = new BABYLON.Scene(engine);

var baseUrl = "";

    BABYLON.SceneLoader.ImportMeshAsync(null, baseUrl + "BoomBox/glTF/", "BoomBox.gltf", scene).then(function (result) {
        result.meshes[0].position.x = 0.01;
    BABYLON.SceneLoader.ImportMeshAsync(null, baseUrl + "Avocado/glTF/", "Avocado.gltf", scene).then(function (result) {
        result.meshes[0].position.x = -0.01;
        result.meshes[0].position.y = -0.01;
]).then(() => {
    scene.createDefaultCameraOrLight(true, true, true);
    scene.activeCamera.alpha += Math.PI;

Demo -