Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

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


function can use to add more code to execute on completion or that the caller can use to
check the state of the promise. The timeoutAsync function is called, which performs the time-
out action but doesn’t execute application-specific code. Next, the application-specific code is
added to the promise object by calling the done method on the promise object and passing
the code. When you subscribe to the promise object by using the done method, your code
is executed upon successful completion (resolved, not rejected). Finally, the promise object is
returned to the caller.
When this code is executed, there is a two-second delay, and then a pop-up is displayed
with the message, “done!”
You can call the done method multiple times to add more code to be executed upon
successful completion. The order in which you add the code is how the code will execute. In
addition, the code is guaranteed to execute only once because you cannot change the state
after it’s been changed to resolved or failed.

Handling failure


You can execute code upon failure of the asynchronous call by subscribing to the promise
object and using the fail method. The following example demonstrates the use of the fail
method to execute code upon failure, which is the rejected state.
function abcAsync() {
var promise = timeoutAsync(2000);
promise.done(function () { alert('done!') });
promise.fail(function () { alert('failed!') });
return promise;
}

Handling completion cleanup


In addition to subscribing to success or failure, you can add code to execute when the asyn-
chronous call has completed, regardless of success or failure. Subscribe to the promise object
by using the always method. The following example demonstrates the use of the always
method.
function abcAsync() {
var promise = timeoutAsync(2000);
promise.always(function () { alert('always!') });
promise.done(function () { alert('done!') });
promise.fail(function () { alert('failed!') });
return promise;
}

Behind the scenes is a done collection of functions and a failed collection of functions.
One of the collections of functions is executed upon the change from pending to either
resolved or rejected. When you use the always method to add code to execute upon comple-
tion, your function is added to the done and failed collections. In this example, you see the
Free download pdf