One of the interesting things about working with async APIs is that, well, they’re asynchronous. You never quite know when they’ll start nor when they’ll complete. When working in JavaScript, also not always obvious how to stop an operation once it gets going. In other languages, where you have direct access to the IAsyncOperation and related interfaces that derive from IAsyncInfo, it’s quite clear that you can call IAsyncInfo.Cancel to do the job.

Async operations are projected into JavaScript as promises, and it’s there that you have to look. Simply, the promise object has a cancel method, which will internally invoke the IAsyncInfo method.

I saw a forum post today asking how to tell which page in an JavaScript app started an async operation, as the operation could complete after the app has navigated to a new page. It’s really not the right question, because if a page starts any async operations that are that page-specific (that is, would only be processed by that page alone), then you should cancel the promises for each operation in the page’s unload method. If the operation isn’t page-specific, then it doesn’t belong inside a page control in the first place.

Comments are closed