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.

Obviously this didn't work. 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 final approach is solving the unwanted behaviour by mostly removing any possible event driven behaviour and handling control in a full imperative way, explicitly calling functions in the expected sequence.

This works but it's not leveraging Javascript nature, and the code itself results harder 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 job, contributing to our overarching business flow.

This alternative solution is probably also more idiomatic and as a consequence more coincise and easier to read.