Async.js

Async.js became the industry standard for handling callbacks before Promises went viral. Today, most of async.js utilities can be replaced with idiomatic usage of advanced Promise implementations, with all of it richness – promisification, convenient adapters for callbacks, long stack traces.

Bluebird exposes common array operations like map, filter, each. These methods take 3 arguments – array (or Promise resolving to array), function applied to each element and concurrency – maximal number of functions running at once, in manner similar to async.fnLimit family.

Some async.js methods for collections can’t be emulated using basic Promise-based code – methods like ‘sortBy’, ‘transform’ tend to be pain in ass. We’ll discuss how to marry async.js and Bluebird later.

Retry

It’s often convenient to retry failed task. It’s quite easy to write in synchronous manner, but writing it in asynchronous way can be mind-boggling, especially when concurrency or parallelism comes in the hand.

Can you see what is wrong with this code? It runs to successful completion of all tasks, or first rejection. If acquiring resource is time-consuming, we’ll introduce to our code race conditions – code execution (in our case – retry) will continue regardless if non-faulty task released it’s resources.

Bluebird offers powerful mechanisms to prevent this issue. Disposers allow us to automatically clean resources, similar to RAII pattern, but for better comparision with async we will assume that our functions task1 and task2 clean their resources on completed execution.