Skip to content

Instantly share code, notes, and snippets.

@avastamin
Created March 13, 2017 10:06
Show Gist options
  • Save avastamin/93276d3c8d5da7cee5924b0159e8ab31 to your computer and use it in GitHub Desktop.
Save avastamin/93276d3c8d5da7cee5924b0159e8ab31 to your computer and use it in GitHub Desktop.
Ajax with Promises
function generatListItems(employees) {
var statusHTML = '';
for (var i=0; i<employees.length; i += 1) {
if (employees[i].inoffice === true) {
statusHTML += '<li class="in">';
} else {
statusHTML += '<li class="out">';
}
statusHTML += employees[i].name;
statusHTML += '</li>';
}
return statusHTML;
}
function generateUnorderedList(listItems) {
return '<ul class="bulleted">' + listItems + '</ul>';
}
function addEmployeesToPage(ul) {
document.getElementById('employeeList').innerHTML = ul;
}
function getJSON(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handleResponse;
xhr.onerror = function(error) { reject(error); };
xhr.send();
function handleResponse() {
if(this.readyState === this.DONE)
if(this.status === 200) {
resolve(JSON.parse(this.responseText));
} else {
reject(this.statusText);
}
}
});
}
var p = getJSON('../data/employees.json').then(generatListItems)
.then(generateUnorderedList)
.then(addEmployeesToPage).catch(function(e){
console.log(e);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment