In this unit, you replace the callback-based inplementation of the request() function with an ECMAScript 6 promise-based implementation.
Open js/app.js
in your favorite code editor.
At the top of the file, modify the request()
function definition as follows:
successHandler
and errorHandler
arguments in the function signaturesuccessHandler()
, resolve the promiseerrorHandler()
, 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);
});
};
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);
});
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
Make sure your local http server is started, open a browser and access http://localhost:8080.
The final code for this step is available in this branch.