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.



It occasionally comes up that you need to serially iterate over a synchronous collection, but doing so involves async APIs. For example, you have a vector of StorageFile objects and want to call copyAsync on each of them, one at a time, in the order of the vector.

This can be accomplished with the following code (thanks to Adam Comella for this solution). Assuming that storageItems is the list over which you want to iterate and destination is the folder into which you want to copy those items, you can do this:

var storageItemsPromise = WinJS.Promise.as();
storageItems.forEach(function (item) {
     storageItemsPromise = storageItemsPromise.then(function () {
         return item.CopyAsync(destination);
     });
});
// Call done so that if CopyAsync throws an exception, it’ll cause the app to terminate
storageItemsPromise.done();