Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

Using Windows Runtime Asynchronous Methods

Many Windows Runtime methods, especially methods that might take a long time to complete, are asynchronous. These methods generally return an asynchronous action or operation (for example, [Windows.Foundation.IAsyncAction], [Windows.Foundation.IAsyncOperation], [Windows.Foundation.IAsyncActionWithProgress], or [Windows.Foundation.IAsyncOperationWithProgress]). These methods are represented in JavaScript by the CommonJS/Promises/A pattern. That is, they return a Promise object that has a then function, for which you must provide a completed function that handles the result if the operation succeeds. If you don't want to provide an error handler, you should use the done function instead of the then function.

Important note Important

Windows Runtime features are not available for apps that run in Internet Explorer.

In the following example, the then function takes a parameter that represents the completed value of the createResourceAsync method.

client.createResourceAsync(uri, description, item)
    // Success.
    .then(function(newItem) { 
        console.log("New item is: " + newItem.id);
            });

In this case, if the createResourceAsync method fails, it returns a promise in the error state, but does not throw an exception. You can handle an error by using the then function as follows.

client.createResourceAsync(uri, description, item)
    // Success.
    .then(function(newItem) { 
              console.log("New item is: " + newItem.id);
          }
          function(err) {
              console.log("Got error: " + err.message);
          });

If you don't want to handle the error explicitly, but do want it to throw an exception, you can use the done function instead.

client.createResourceAsync(uri, description, item)
    // Success.
      .done(function(newItem) { 
               console.log("New item is: " + newItem.id);
            });

You can also display the progress made towards completion by using a third function.

client.createResourceAsync(uri, description, item)
    // Success.
      .then(function(newItem) { 
               console.log("New item is: " + newItem.id);
            },
    // Error.
            function(error) { 
               alert("Failed to create a resource.");
            },
    // Progress.
            function(progress, resultSoFar) { 
               setProgressBar(progress);
            });

For more information about asynchronous programming, see Asynchronous programming.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.