Book Image

Mastering JavaScript Promises

Book Image

Mastering JavaScript Promises

Overview of this book

Table of Contents (16 chapters)
Mastering JavaScript Promises
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Combination in Q


With Q, you have a unique facility in Node.js to write cleaner and manageable code if you want to combine a list of array of promises. This can help you to write a more complex level of sequential data structure in a more manageable way. How can we get there? Use all. Consider the following example:

return Q.all([
    eventAdd(2, 2),
    eventAdd (10, 20)
]);

The Q.all([func1(), func2()]); function will be the generic form of the preceding code. You can also use spread to replace then. Can we replace another new thing with Q? Not really! The spread function spreads the values over the arguments of the fulfillment handler. For the rejection handler, it will get the first signal of failure. So, any of the promises destined to fail first will get it handled by a rejection handler:

function eventAdd (var1, var2) { 
    return Q.spread([var1, var2], function (var1, var2) {
        return a + b;
    })
}

Q.spread(). Call all initially

return getUsr() .then(function (userName) ...