Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

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


The following example is a rewrite of the previous example; the deferred object notifies its
subscribers of progress change.
function abcAsync() {
var deferred = $.Deferred();
var count = 0;
var firstPromise = timeoutAsync(2000);
var secondPromise = timeoutAsync(3000);
var thirdPromise = timeoutAsync(1000);
var fourthPromise = timeoutAsync(1234);
firstPromise.always(function () { deferred.notify( ++count); });
secondPromise.always(function () { deferred.notify(++count); });
thirdPromise.always(function () { deferred.notify(++count); });
fourthPromise.always(function () { deferred.notify(++count); });
$.when(firstPromise, secondPromise, thirdPromise, fourthPromise)
.then(function () { alert('done!'); deferred.resolve(); },
function () { deferred.reject(); });
return deferred.promise();
}

In this example, the count variable is initialized to zero, and then, upon completion of each
asynchronous call, the count variable is incremented. The following code calls the abcAsync
function and displays the progress.
function runAbcAsync() {
var promise = abcAsync();
promise.progress(function (msg) { alert(msg); });
return promise;
}

In this example, as the progress is updated, a pop-up is displayed with the numeric value.
The asynchronous calls can complete in any order.

Conditional asynchronous calls


Sometimes, you need to make an asynchronous call conditionally. In the case of chained
operations in which a middle operation is conditionally executed, you need a way to splice
in (or out) the operation. Consider the following example, in which the third asynchronous
operation is conditionally executed.
function abcAsync(includeThird) {
var firstPromise = timeoutAsync(2000);
var secondPromise = firstPromise.pipe(function () {
return timeoutAsync(3000);
});
var thirdPromise = includeThird? secondPromise.pipe(function () {
return timeoutAsync(1000);
}) : secondPromise;
var fourthPromise = thirdPromise.pipe(function () {
return timeoutAsync(1234);
});
fourthPromise.done(function () {
firstPromise.done(function () { alert('done!') });
Free download pdf