Scripting - sequencing without callback hell

Hi @Nikolay,

I want to run the following code 4 times to have a boy travel in a square:

    boy.transition.moveBy( 
        new Vector3( 0, 5, 0 ), // local place to move to
        3, // duration in seconds
        function(){
            boy.transition.rotateLocal(
                new Vector3( 0, 0, 1 ),
                90*(Math.PI/180),
                2
            )
            boy.animation.play('Dance fun')
        }
    );

However, when running the function through a for loop, everything executes (almost) at the same time.

Without reverting to some kind of callback function loop hell or Time.schedule, is there an easy way to sequence such things? Promises?

Thanks in advance!

Geoff @ TechLeap

Hi @techleapnz!

Promises can be an option for sure. While we have no promises in transition API, you can wrap callbacks with promises like this:

function move(item: BaseItem): Promise<BaseItem> {
    return new Promise((resolve, reject) => {
        item.transition.moveBy(new Vector3(-5, 0, 0), 1, () => {
            item.transition.rotateLocal(new Vector3(0, 0, 1), Math.PI / 2, 1, () => {
                resolve(item)
            })
        })
    });
}

move(cube)
    .then(move)
    .then(move)
    .then(move)
2 Likes

Thanks for this @Ilya_Shkuratov!

Geoff @ TechLeap

As a side-note, how does the CoBlocks interpreter handle sequencing? Is it using a similar structure?

You can also use async/await feature of TS and ES languages. Like following:

async function moveCube() {
   await move(cube);
   await move(cube);
   await move(cube);
}
1 Like

We have our own interpreter for CoBlocks that has the ability to suspend execution and then resume it, based on state machine (so we can tell that CoBlocks interpreter implements stackful coroutines). Blocks like ‘move item’ use this ability to suspend execution right after motion starts and resume it as motion completes. The mechanism behind this is quite usual and can be found in many languages like C#, Kotlin, Python, JavaScript, etc. Please note that CoBlocks is not based on JavaScript and CoBlocks scripts aren’t translated to JavaScript before execution.

1 Like

Thanks for all this! Great to pick up some of these ES6 pointers, as I never really got to play with modern JS frameworks which utilise these improvements as part of my web dev work.

So if CoBlocks isn’t using JS at runtime, it’s using… WebAssembly?

No, we don’t use WebAssembly. I meant that we interpret CoBlocks programmatically, we don’t generate JavaScript from it.

1 Like