Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 1: Asynchronous operations using jQuery and WinJS CHAPTER 9 395


function fetchAjaxAsync(url, callback, errorCallback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
processResult();
}
else {
errorCallback(new Error(xhr.statusText));
}
}
}
xhr.open(url, "GET", true);
xhr.send();
}
In this example, passing a true value to the open method indicates that asynchrony is best.
In addition, the onreadystatechanged event is assigned a function that executes whenever
the XMLHttpRequest object changes state. When the state has a value of 4 , the operation is
complete and the status is checked for an error. Because this is an asynchronous operation,
the program doesn’t wait when it calls the send method. Instead, the program proceeds to
the next line and exits the fetchAjaxAsync function. When the result is available, a call to the
processResult function is made, and the result is passed. It’s as though the asynchronous call
is pushing the result to the code that will process it.
This code block is certainly larger than the synchronous code block. It’s also a bit harder to
read, but the benefit is that there is no blocking, so the program remains fast and fluid.
When you have code that needs to chain several asynchronous calls, so each call must
complete before the next call starts, you want to create an asynchronous call to a sequence
of calls. This gets difficult quickly. Currently, the fetchAjaxAsync function is somewhat generic;
you pass in the parameters and get a result. However, if you want to chain additional calls,
you might need to modify this code to make it more specific to the task you’re trying to
accomplish. The promise object helps solve these problems and allows operations to chain
easily.

Creating jQuery promise objects by using $.Deferred()


You can create a promise object by using the $.Deferred method. It seems a bit strange that
the method name is not called $.Promise(), but $.Deferred() returns a deferred object that
wraps the promise object with the functionality to control the promise object, as shown in
Figure 9-1. The creator of the promise object controls the state of it by calling one of the
methods on the deferred object. The methods that end with “with” pass data to the promise
object’s subscribers. The creator of the deferred object can execute the promise method on
the deferred object to get the promise object, which is read-only. Code that references the
promise object can subscribe to state changes on that object but cannot modify its state.
For example, calling the done method on the promise object enables you to pass a function
containing code that executes when the promise object is resolved (completed).
Free download pdf