Lesson 1: Asynchronous operations using jQuery and WinJS CHAPTER 9 399
thirdPromise.done(function () {
var fourthPromise = timeoutAsync(1234);
fourthPromise.done(function () {
firstPromise.done(function () { alert('done!') });
});
});
});
});
return firstPromise;
}
To solve the problem, implement chaining by using the pipe function on the promise
object. The following code is a rewrite of the previous example by using the pipe function to
eliminate nesting.
function abcAsync() {
var firstPromise = timeoutAsync(2000);
var secondPromise = firstPromise.pipe(function () {
return timeoutAsync(3000);
});
var thirdPromise = secondPromise.pipe(function () {
return timeoutAsync(1000);
});
var fourthPromise = thirdPromise.pipe(function () {
return timeoutAsync(1234);
});
fourthPromise.done(function () {
firstPromise.done(function () { alert('done!') });
});
return fourthPromise;
}
In this example, the fourthPromise object is correctly returned so the caller can know when
all code is completed. The calling function can also call the done, fail, or always methods on
the returned promise object to add code to execute upon completion.
In the nested example is a 6-second delay before the fourthPromise object is created. Even
if the fourthPromise variable were in scope, this would be a problem for the calling code that
might want to subscribe to the returned promise object immediately, which will be null.
The pipe method immediately creates a promise object that can be subscribed to and
properly returned to the caller. This is interesting because timeoutAsync(1234) still isn’t called
for 6 seconds, and that call was creating the fourthPromise object. The pipe method created
a proxy object and returned it, but after 6 seconds, the call to timeoutAsync(1234) created a
promise object, which was then attached to the original proxy object.
There’s more to this story, however. If the first asynchronous call fails, the failure is auto-
matically passed to the piped promise object in the chain. You don’t require extra code to
deal with this. You can subscribe to the fail of the fourthPromise object, and you will auto-
matically be notified if any asynchronous call in the chain failed.