As 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?
As 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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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