Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

396 CHAPTER 9 Asynchronous operations


FIGURE 9-1 he Deferred and Promise objectsT

The following is an example of using the $.Deferred() method to set a timeout that a user
can subscribe to by using the methods on the promise object.
function timeoutAsync(milliseconds) {
var deferred = $.Deferred();
setTimeout(function () { deferred.resolve(); }, milliseconds);
return deferred.promise();
}

In this code example, the function name ends with Async as a convention to help the
developer understand that an asynchronous call is being made in this function. A deferred
object is created by using the $.Deferred method and assigned to the deferred variable.
Next, the JavaScript global function setTimeout is called, which has a function parameter
and a timeout milliseconds parameter. The function parameter contains the code to execute
when the timer expires. No application-specific code is in the function. Instead, the resolve
method is called on the deferred object to indicate the completion of the timer. Calling the
resolve method on the deferred object changes the state of the promise object to resolved
and executes all code that was attached to the promise object by using the done method.
In addition to the resolve method, you can call the reject method to indicate a failure of the
asynchronous function. The following is an example of the use of the timeoutAsync function.
function abcAsync() {
var promise = timeoutAsync(2000);
promise.done(function () { alert('done!') });
return promise;
}

In this example, the function name also ends with Async to indicate that it’s asynchronous.
It’s important to keep this convention and always return a promise object that the called
Free download pdf