Promisifying XMLHttpRequest

In this unit, you replace the callback-based inplementation of the request() function with an ECMAScript 6 promise-based implementation.

Steps

  1. Open js/app.js in your favorite code editor.

  2. At the top of the file, modify the request() function definition as follows:

    • Remove the successHandler and errorHandler arguments in the function signature
    • Modify the function body to return an ECMAScript 6 promise
    • Instead of calling successHandler(), resolve the promise
    • Instead of calling errorHandler(), reject the promise

    The request() function definition should now look like this:

    let request = obj => {
        return new Promise((resolve, reject) => {
            let xhr = new XMLHttpRequest();
            xhr.open(obj.method || "GET", obj.url);
            if (obj.headers) {
                Object.keys(obj.headers).forEach(key => {
                    xhr.setRequestHeader(key, obj.headers[key]);
                });
            }
            xhr.onload = () => {
                if (xhr.status >= 200 && xhr.status < 300) {
                    resolve(xhr.response);
                } else {
                    reject(xhr.statusText);
                }
            };
            xhr.onerror = () => reject(xhr.statusText);
            xhr.send(obj.body);
        });
    };
    
  3. Modify the call to the request() function. Replace the old callback functions with the ECMAScript 6 .then() and .catch() syntax.

    The call to the request() function should now look like this:

    request({url: "employees.json"})
        .then(data => {
            let employees = JSON.parse(data);
            let html = "";
            employees.forEach(employee => {
                html += `
                    <div>
                        <img src='${employee.picture}'/>
                        <div>
                            ${employee.firstName} ${employee.lastName}
                            <p>${employee.phone}</p>
                        </div>
                    </div>`;
            });
            document.getElementById("list").innerHTML = html;
        })
        .catch(error => {
            console.log(error);
        });
    
  4. On the command line, make sure you are in the es6-tutorial-data directory, and type the following command to build the app:

     npm run webpack
    
  5. Make sure your local http server is started, open a browser and access http://localhost:8080.

Solution

The final code for this step is available in this branch.

comments powered by Disqus