Right now there are two main ways to handle async control flow in JS. We’ll take a short look on them. All functions are written as async for demonstration reasons.
Callbacks are the main way to handle async operations since very early Node.js versions. They follow the pattern
This way of nesting function that depend on each other is often referenced as “callback hell”:
Advanced Callback Handling
async module has very good support for advanced callback handling and their scheduling.
Cons: Flow of the program / Error handling can be confusing to read.
Pro: low level
Tip: use named functions to avoid callback hell / deep callback nesting
Promises are similar to to Futures in Java and C#. They can be used to wrap callback APIs. They are part of the ES6 spec and Node has native Promise support since v4.0.0.
Advanced Control Flows with Promises
For queuing multiple Promises the module
bluebird is a great choice. However, there are some nice functions available out of the box.
Multiple async operations
Let’s say we have a few Network requests and want to continue once all are finished. jQuery supports a Deferreds/Promises for Network calls.
Pro: easier to avoid callback hell, error handling easier to reason about
Cons: a new API to learn
The Future: async / await
ES8 will probably come with async/await support in 2018. It will take some time until it is implemented by all major platforms.
The draft is located at https://tc39.github.io/ecmascript-asyncawait and it can still change.