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

Static methods of Q


Typecasting of promises objects is a must and you must have to convert promises generated from different sources in Q type promises. This is because of the simple fact that not all promise libraries have the same warranties as Q and certainly don't provide all of the same methods.

//using when 
return Q.when(AmIAvalueOrPromise, function (value) {
}, function (error) {
});
//The following are equivalent:
return Q.all([a, b]);
return Q.fcall(function () {
    return [a, b];
})
.all();

Most libraries only provide a partially functional then method. Q, on the other hand, is quite different to others:

return Q($.ajax(...))
.then(function () {
});

If there is any way that the promise you have got is not a Q promise as provided by your library, you should wrap it using a Q function. You can even use Q.invoke(); as shorthand, as shown in the following code:

return Q.invoke($, 'ajax', ...)
.then(function () {
});