Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

400 CHAPTER 9 Asynchronous operations


Quick check
■■You want to chain several asynchronous calls together. Which promise method
will you use?

Quick check answer
■■Use the pipe method on the promise object.

Parallel execution using $.when().then()


The previous examples exhibited chained operations by which each operation waits for the
previous operation to complete before starting. For example, the previous example took
7.234 seconds to complete. Sometimes this is necessary, but you might want to run the opera-
tions simultaneously. If you execute each operation in parallel, how can you know that all four
operations completed?
You can use the $.when() method to indicate completion of multiple asynchronous opera-
tions. The $.when() method is non-blocking, so it’s usually used with a deferred object. In the
following example, the previous example is rewritten to run all four operations in parallel.
function abcAsync() {
var deferred = $.Deferred();
var firstPromise = timeoutAsync(2000);
var secondPromise = timeoutAsync(3000);
var thirdPromise = timeoutAsync(1000);
var fourthPromise = timeoutAsync(1234);
$.when(firstPromise, secondPromise, thirdPromise, fourthPromise)
.then(function () { alert('done!'); deferred.resolve(); },
function () { deferred.reject(); });
return deferred.promise();
}

The $.when() method accepts promise parameters and monitors for all to complete. If
a parameter is not a promise object, it is immediately considered to be completed. The
$.when() method creates its own promise that is passed to the then() method, which first
accepts a function to be executed upon success and then accepts a function to be executed
upon failure. Not shown here is that the then() method also accepts a third function param-
eter to be executed when the progress changes.

Updating progress


The deferred object can also notify its promise object when progress has changed. It does
this by executing the notify method of the deferred object when you want to update the
progress.
The promise object has a progress method that accepts a function called when the notify
method is executed.
Free download pdf