Partilhar via


Quickstart: Using promises (HTML)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

You can make your UI more responsive by doing some kinds of processing asynchronously, leaving the app's UI thread free to respond to user input. This quickstart shows how to do asynchronous programming in your Windows Runtime apps.

Asynchronous APIs in the Windows Library for JavaScript and Windows Runtime are represented in JavaScript as promises, which are defined in the Common JS Promises/A proposal. You can find more information about asynchronous programming and promises in Asynchronous programming in JavaScript

You can make your code more robust by including some error handling when you use promises. This quickstart shows only one of the many ways you can handle errors, but you can learn more in How to handle errors with promises in JavaScript.

Prerequisites

To complete this quickstart, you need to be able to create a basic Windows Runtime app that uses WinJS. For help creating your first app, see Create your first Windows Runtime app using JavaScript.

Instructions

1. Using a function that returns a promise

Let's look at a simple example of a promise. We'll create an app that takes a URL, attempts to contact the site, and then reports whether it succeeded.

  1. Create a blank Windows Runtime app named TestPromise.

  2. Add an INPUT element.

    <div>
    <input id="inUrl" />
    </div>
    
  3. Add a DIV element that displays the result for the URL.

    <div id="divResult">Result</div>
    
  4. Add the following styling instructions to "default.css".

    input {
    
    }
    
  5. Add a change handler for the INPUT element. You can do this as part of the WinJS.Utilities.ready function. It's called immediately after the DOMContentLoaded event, which fires after the page has been parsed but before all the resources are loaded.

    Add the following code to the app.onactivated event handler in "default.js".

    WinJS.Utilities.ready(function () {
        var input = document.getElementById("inUrl");
        input.addEventListener("change", changeHandler);
      }, false);
    
  6. In the change handler, call xhr, passing in the URL the user entered, and update the result DIV with the result. The xhr function returns a Promise, so we can use the then or done function of the promise to update the UI. The then method is executed as soon as the xhr function has either successfully made the XmlHttpRequest or has gotten an error. The done function is the same, except that it is guaranteed to throw any error that is not handled inside the function.

    You can provide up to three parameters to then or done: a completed function that handles the promise if it was fulfilled without errors, an error function that handles errors, and a progress function that displays the progress of the promise toward completion. Right now we'll just show how to add the completed function, and save the error handling for another step. The completed function sets the background color of the result DIV to green and sets the text to "Success".

    function changeHandler(e) {
        var input = e.target;
        var resDiv = document.getElementById("divResult");
    
        WinJS.xhr({ url: e.target.value }).then(function completed(result) {
            if (result.status === 200) {
                 resDiv.style.backgroundColor = "lightGreen";
                 resDiv.innerText = "Success";
             }
         });
     }
    
  7. Build and debug the app and then enter a URL. (After you enter the URL, you may need to click outside the INPUT control for the change event to occur.) If the URL is valid, the result DIV should turn green and display "Success". If you enter an URL that isn't valid, nothing happens.

2. Handling errors

  1. To do error handling, add an error function inside the then function that sets the background color of the Success button to red and the text to the error message, if there is one.

    function changeHandler(e) {
        var input = e.target;
        var resDiv = document.getElementById("divResult");
    
        WinJS.xhr({url: e.target.value}).then(
            function fulfilled (result) {
                if (result.status === 200) {
                    resDiv.style.backgroundColor = "lightGreen";
                    resDiv.innerText = "Success";
                }
            }, 
            function error(e) {
                resDiv.style.backgroundColor = "red";
    
                if (e.message != undefined) {  // If the URL is really malformed or blank.
                resDiv.innerText = e.message;
                }
                else if (e.statusText != undefined) { // If an XmlHttpRequest is made.
                    resDiv.innerText = e.statusText;
                }
                else {    
                    resDiv.innerText = "Error";
                }
        });
    }
    
  2. Build and debug the app. If you enter an invalid URL, the button will turn red and display the error message.

Summary and next steps

In this quickstart you learned how to use a function that returns a promise and how to perform one kind of error handling.

The following topics explain more complex scenarios with promises:

Asynchronous programming in JavaScript