Flow control in Javascript

less than 1 minute read

Mark Needham recently wrote a blog post on how his team worked around a Javascript asynchronous unwanted behaviour.

They want to iterate over a collection, executes some code for each element of the collection and only when all the collection has been traversed execute a final step.

This didn’t work as expected. Due to the asynchronous nature of Javascript the do something with grid block is invoked before the grid itself is filled and nothing interesting happens.

Their solution to this was removing any possible event driven behaviours and handling control in a fullly imperative way, explicitly calling functions in the expected sequence.

This works but it’s not leveraging Javascript nature; also the code itself results harder to understand then what it should be.

How the same problem can be solved embracing asynchronous thinking ? The way to achieve control flow in Javascript is with events.

When a block is completed it emits an event. All the interested parties will be listening to the specific event and execute their specific task, contributing to our overarching business flow. This alternative solution is probably also more idiomatic and as a consequence more coincise and easier to read.