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.

As with C#, there are additional structures for when you’re nesting async operations, supporting<br />

cancellation, and reporting progress. I will leave the details to the documentation. See Asynchronous<br />

Programming in C++ and Task Parallelism.<br />

Sidebar: Joining Promises<br />

There’s one detail from the Image Manipulation example that takes advantage of having all the<br />

async operations managed through promises. In the app, we show a horizontal progress indicator<br />

before starting all the async operations with the Counting Perf (Async) button:<br />

function testPerfAsync() {<br />

showProgress("progressAsync", true);<br />

//...<br />

}<br />

We want this control to stay visible while any of the async operations are still running,<br />

something that’s easily done with WinJS.Promise.join. What’s interesting to point out here is that<br />

we can already have called then or done on those individual promises, which simply means that<br />

we’ve wired up separate handlers for those individual operations. The handlers we give to join,<br />

then, are just wired up to the fulfillment of all those promises together:<br />

promiseJS.done(function (sum) {<br />

// Output for JS worker<br />

}<br />

promiseCS.done(function (sum) {<br />

// Output for C# component<br />

})<br />

promiseCPP.done(function (sum) {<br />

// Output for C++ component<br />

});<br />

WinJS.Promise.join([promiseJS, promiseCS, promiseCPP]).done(function () {<br />

// Hide progress indicator when all operations are done<br />

showProgress("progressAsync", false);<br />

});<br />

In this code you can see how much we simplify everything by wrapping a worker’s message<br />

mechanism within a promise! Without doing so, we’d need to maintain one flag to indicate<br />

whether the promises were fulfilled (set to true inside the join) and another flag to indicate if the<br />

worker’s results had been received (setting that one to true inside the worker’s message handler).<br />

Inside the join, we’d need to check if the worker was complete before hiding the progress<br />

indicator; the worker’s message handler would do the same, making sure the join was complete.<br />

This kind of thing is manageable on a small scale but would certainly get messy with many<br />

parallel async operations—which is the reason promises were created in the first place!<br />

741

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

Saved successfully!

Ooh no, something went wrong!