What's the best way to emulate coroutines before version 5.0?

Thanks, Ranaan! That’s definitely an option.

However, I figured out an “in-house” solution (in the sense that it requires adding nothing new or external):

private static async LerpPositions(
    target: IPositionable,
    positions: BABYLON.Vector3[],
    duration: number,
    scene: BABYLON.Scene
) {
    const individualDuration = duration / positions.length;
    for (let position of positions) {
        await this.LerpPosition(target, target.position, position, individualDuration, scene);
    }
}

private static async LerpPosition(
    target: IPositionable,
    start: BABYLON.Vector3,
    end: BABYLON.Vector3,
    duration: number,
    scene: BABYLON.Scene
): Promise<void> {
    return new Promise<void>((resolve, _reject) => {
        const timer = new Timer(duration, false);
        const lerp = () => {
            const deltaTime = scene.deltaTime;
            if (!deltaTime) return;

            timer.Increment(deltaTime);
            target.position = BABYLON.Vector3.Lerp(start, end, timer.elapsed / duration);
        };

        scene.onBeforeRenderObservable.add(lerp);
        timer.onComplete.addOnce(() => {
            scene.onBeforeRenderObservable.removeCallback(lerp);
            resolve();
        })
    });
}

You can see it in action over at the Playground: LerpTestWithoutCoroutines | Babylon.js Playground (babylonjs.com).

Is this the best way to do it? Probably not. I’m no good at JavaScript. I’m sure the code be improved to be cleaner and more elegant. But it works, at least, and to anyone who has something to add to it: please, feel free!


P.S. What’s the recommended route for upgrading to 5.0 in an NPM environment? Do I simply edit my package.json, or should I clone the relevant branch from the GitHub repo?