The Synchronous Promise

Pontus Alexander
ReCreating Megaman 2 using JS & WebGL
2 min readJul 29, 2016

In my game engine I have helper methods on objects that receive time that allows you to bind something to them for a certain amount of time or wait for a certain amount of time. Let me show the scene class as an example.

In the snippet below I’m using the doFor method on the scene to move the camera 120 units on the X-axis during 5 seconds, then 300 units on the Y-axis for 3 seconds.

The doFor method returns a Promise that resolves when the given time has elapsed. Since the game loop runs on every requestAnimationFrame I can reliably use the regular asynchronous Promise.

However, I ran into a problem when I wanted to write tests that runs faster than realtime. On the World object I have a method called updateTime that simulates the game for the given period of time using a fixed time step.

Since an asynchronous Promise can never resolve before the updateTime method has finished, I can not rely on the chained (then’ed) function being called at a deterministic point in the simulation.

When I realised this I either had to decide not use Promises. Or I could “invent” Synchronous Promise. The first time I said this out loud I said it as a joke. But then it kinda felt like it could make sense, so I decided to experiment with it.

After spending a day learning all the internals of normal Promises so that I could implement it myself, I wrote a Promise compatible Synchronous Promise that works exactly like a Promise except that instead of deferring to the next call stack, it hooks into the call stack at resolve time.

This means I can write chains using the syntax of Promises and have a deterministic execution point.

It might be that what I have done here is implement an known pattern under a different name and that this makes absolutely no sense. If you know so, please share. :)

--

--

Pontus Alexander
ReCreating Megaman 2 using JS & WebGL

I’m a software engineer, living in Stockholm. I write about random things that interest me.