Learn about Node Q package - NPM
In node.js, promise can mitigate the pyramid of Doom, lets take the below example
step1(function(value1){
step2(value1, function(value2){
step3(value2, function(value3){
step4(value3, function(value4){
//Do something
});
});
});
});
with Q library it can be flatten in the below way
Q.fcall(promisedStep1)
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function(value4){
}).catch(function(err){
}).done();
Getting Started
The Q module can be loaded as
<script> tag (Creating Q global variable)
A Node.js and commonJS module, available in npm as the q package
Q can exchange promises with jQuery, Dojo, When.js, WinJS and more...
Examples
promiseMeSomething()
.then(function (value) {}, function (reason) {});
If promiseMeSomething returns a promise that gets fulfilled later with a return value(first function called)
If promiseMeSomething returns a error that gets operated by second function.
Note that resolution of a promise is always asynchronous that is fulfilled or rejection handler
will always be called in the next turn of the event loop(i.e process.nextTick)
Propagation
var outputPromise = getInputPromise()
.then(function(input){}, function(reason){});
The outputPromise variable becomes a new promise for the return value of either handler.
Since a function can only either return a value or throw an exception, only one hndler will
ever be called and it will be responsible for resolving outputPromise