394 CHAPTER 9 Asynchronous operations
This lesson focuses on jQuery’s deferred and promise objects for controlling execution of
asynchronous execution.
After this lesson, you will be able to:
■■Describe asynchrony, using jQuery.
■■Implement asynchronous operations by using the promise object.
Estimated lesson time: 20 minutes
Using a promise object
The pattern for working with asynchrony is to use a promise object. The promise (also known
as a future or deferred) object provides a mechanism to schedule work to be done on a value
that might not yet be computed. The promise object can be in one of three states: pend-
ing, resolved, or rejected. It starts in the pending state, moves to either resolved or rejected,
and then does not change. The benefit is that it enables you to write non-blocking logic that
executes asynchronously without having to write a lot of synchronization and plumbing code.
CommonJS, which defines a specification for using JavaScript everywhere, defines the
Promise/A specification that many JavaScript technologies implement. The promise object
is implemented in WinJS and jQuery. After you understand the concept of a promise object,
you’ll find that it’s easy to implement using any technology.
Consider the following synchronous code example that uses the XMLHttpRequest object
to make an AJAX call.
function fetchAjaxSync(url) {
var xhr = new XMLHttpRequest();
xhr.open(url, "GET", false);
xhr.send();
if (xhr.status == 200) {
return xhr;
}
throw new Error(xhr.statusText);
}
In this example, passing a value of false to the open method causes the code to run syn-
chronously. When the send method is called, the program waits until the result is available
and then proceeds to the next line of code, where the returned status is checked to deter-
mine whether an error occurred. In this example, the result can just be returned to the caller
that is waiting for the operation to complete. It’s as though the caller is pulling the result from
the fetchAjaxSync function.
The code block is compact, easy to read, and simple. In this example, the AJAX call takes
30 seconds to complete, and other code cannot run. The result is that the screen appears
to lock up until the AJAX call has completed. This is the case for providing an asynchronous
programming model. The following code illustrates the rewrite.
Key
Te rms