In our #lillygram application cloud backend we have a bunch of async tasks that need to happen in strict sequence. This blogpost explain why we chose the async.js Node.js-library for our asynchronous tasks.
A common pitfall, which we also fell into, is to nest function calls into callbacks, and let the inner-most callback be responsible for what to do once all calls have completed. In an attempt to keep things tidy we tried to declare and assign all callbacks to named variables before nesting the calls. This helps a little bit, but still leaves the code messy and unintuitive. But it starts to feel a little irky when we decide to change the order of calls. Should we also change the order of the declarations?
In the end, it seems that the best way to go is to throw a reference to each function into a list, iterate over this list, and call each in turn. In fact, that’s what async.js, does with its ‘series‘ method.
Intermediate handling in async.js is left to the individual function. In order to maintain flexibility, we persist the outcome of each function within the scope the async tasks, allowing functions down the chain to access the data it needs.
Here’s a highly simplified example implementation of async.js
[CodePen height=475 show=js href=FguLr user=testower ]