23.01.2018 Views

MICROSOFT_PRESS_EBOOK_PROGRAMMING_WINDOWS_8_APPS_WITH_HTML_CSS_AND_JAVASCRIPT_PDF

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Sequential Async Operations: Chaining Promises<br />

In the previous code example, you might have noticed how we throw exceptions whenever we don’t get<br />

a good result back from any given async operation. Furthermore, we have only a single error handler at<br />

the end, and there’s this odd construct of returning the result (a promise) from each subsequent async<br />

operation instead of just processing the promise then and there.<br />

Though it may look odd at first, this is actually the most common pattern for dealing with sequential<br />

async operations because it works better than the more obvious approach of nesting. Nesting means to<br />

call the next async API within the completed handler of the previous one, fulfilling each with done.<br />

Here’s how the async calls in previous code would be placed with this approach (extraneous code<br />

removed for simplicity):<br />

captureUI.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.photo)<br />

.done(function (capturedFileTemp) {<br />

//...<br />

local.createFolderAsync("HereMyAm", ...)<br />

.done(function (myFolder) {<br />

//...<br />

capturedFile.copyAsync(myFolder, newName)<br />

.done(function (newFile) {<br />

})<br />

})<br />

});<br />

The one advantage to this approach is that each completed handler will have access to all the<br />

variables declared before it. Yet the disadvantages begin to pile up. For one, there is usually enough<br />

intervening code between the async calls that the overall structure becomes visually messy. More<br />

significantly, error handling becomes significantly more difficult. When promises are nested, error<br />

handling must be done at each level; if you throw an exception at the innermost level, for instance, it<br />

won’t be picked up by any of the outer error handlers. Each promise thus needs its own error handler,<br />

making real spaghetti of the basic code structure:<br />

captureUI.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.photo)<br />

.done(function (capturedFileTemp) {<br />

//...<br />

local.createFolderAsync("HereMyAm", ...)<br />

.done(function (myFolder) {<br />

//...<br />

capturedFile.copyAsync(myFolder, newName)<br />

.done(function (newFile) {<br />

},<br />

function (error) {<br />

})<br />

},<br />

function (error) {<br />

});<br />

},<br />

function (error) {<br />

});<br />

94

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!