Object JavaScript – Promises By Integrating Q with jQuery

6327_image_58FAEDFAAs you have seen in previous posts, a promise in JavaScript represents the result of a task, which may or may not have completed yet. Or in simpler words, what to expect for a JavaScript call.

Q was designed to provide a robust way to provide you ways to write asynchronous code cleanly.

You can integrate the robustness of Q with jQuery promises.

Why Q?

687474703a2f2f6b7269736b6f77616c2e6769746875622e696f2f712f712e706e67As you learned in Asynchronous JavaScript Promises Using Q , you get additional goodness by using Q rather than jQuery’s promises. The main features being:

  • Exception handling
  • Several additional methods give you deep control of the promise
  • An error (or in a promise reject) in one chained thens will be handled “down the chain” by a later

Q with jQuery

When you pass in jQuery into Q, it coerces the jQuery promise into a Q promise that you can then use.

The following code snippet returns a Q promise from a jQuery AJAX or jQuery getJSON call.


var qPromise = Q($.getJSON("data/products.txt"))
.then(function (products) {
$("#products").text(JSON.stringify(products));
});

You can continue to chain the promise and get all the goodness of Q.

Sample Code

You can get sample code for this post in the DevDays GitHub repository: https://github.com/devdays/object-javascript/tree/master/Q

References