402 CHAPTER 9 Asynchronous operations
});
return fourthPromise;
}
In this example, the includeThird variable is passed into the abcAsync function and is
used to determine whether the third asynchronous function should be called. If includeThird
is false, the thirdPromise variable still needs to be assigned a promise to chain the fourth
asynchronous call, so secondPromise is assigned directly to the thirdPromise variable. This
maintains the chain of operations.
When making parallel asynchronous calls, conditionally calling the third operation is done
differently, as shown in the following example.
function abcAsync(includeThird) {
var deferred = $.Deferred();
var firstPromise = timeoutAsync(2000);
var secondPromise = timeoutAsync(3000);
var thirdPromise = includeThird? timeoutAsync(1000) : $.when();
var fourthPromise = timeoutAsync(1234);
$.when(firstPromise, secondPromise, thirdPromise, fourthPromise)
.then(function () { alert('done!'); deferred.resolve(); },
function () { deferred.reject(); });
return deferred.promise();
}
In this example, if includeThird is true, the third asynchronous call is executed and assigned
to the thirdPromise variable. If includeThird is false, $.when() is assigned to the thirdPromise
variable. Remember that $.when() is used at the bottom of the function to indicate that all
asynchronous operations have completed, which creates a new promise that is passed to the
then() method. If you call $.when() with no parameters, a new promise object is created with
its status set to resolved.
NOTE USE THE $.when() METHOD
When you need to create a promise object whose state is resolved, use the $.when()
method.
Lesson summary
■■The deferred object is a wrapper for the promise object. The deferred object provides
control of the promise object, which is read-only.
■■The promise object has the done, fail, always, and progress methods that accept
a function parameter, which enables you to subscribe to state change. The then()
method on the promise object enables you to subscribe to done, fail, and progress.
■■The subscription functions execute a maximum of one time.
■■The state method can be used to get the current state of the promise object.
■■The promise object’s pipe method chains asynchronous operations.