Have you ever need to wait for several, unrelated asynchronous functions or processes on NodeJS in order to met dependencies of a last request/method/function/etc? I’m really sure you have, and it can be a pain if you do not know how to properly handle it. The worst
and common case is having each one of this nested on then previous one.
There is a really easy and common way I’ve seen lately, that is by using Async.js which is not bad, but it is not that good either, mainly cause it is not a standard. If you want (and you should really want!) a standard way to do such tasks (the right way) then you should start using Promises.
Promises provide a well-defined interface for interacting with an object that represents the result of an action that is performed asynchronously, and may or may not be finished at any given point in time. By utilizing a standard interface, different components can return promises for asynchronous actions and consumers can utilize the promises in a predictable manner. Promises can also provide the fundamental entity to be leveraged for more syntactically convenient language-level extensions that assist with asynchronicity.
In this example I’ll be demotrating how to use Q (Promises/B proposal by Kris Kowal) in 3 different use cases: standard functions, NodeJS like functions (callbacks) and finally a simple deferred implementation. Continue reading