If you think that callback hell is a real problem, you obviously missed async module. I know most popular method are probably
async.parallel but my personal favourite is
async.auto. I consider it the ultimate solution to callback hell problem and much more…
Let’s try do this:
- write domain name to a file
- check if the file exists
- read domain name from the file
- check IP address, MX record and reverse address for the domain
- delete the file
- display results
Here’s a typical way do acomplish above:
google.com: -- ip: 188.8.131.52 -- mx: alt1.aspmx.l.google.com -- rev: fa-in-f139.1e100.net
async.auto to the rescue!
Now we’ll do this again but using
As you can see
async.auto takes list of tasks with requirements. Every task is provided with results from required tasks list. If any task pass error argument to callback function, processing stops and final callback is being called with error argument. When all tasks are successfully finished, final callback is called with object containings results.
But that’s not all. There’s a bonus! For example
mx tasks are being executed in parallel, because they don’t depend on each other’s result! If you track dependencies carefully, you’ll see that actual processing scenario is as follows:
As you can see, the code is faster, because everything that can is being executed in parallel. You can also easily change order of execution by modifying dependencies. This should be in core!