Last active
February 16, 2017 19:30
-
-
Save edu222/f832bd597ae83476e4cbc9d8a5f736f7 to your computer and use it in GitHub Desktop.
Promise Based XHR Request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(xhr.readyState === 4) { | |
if (xhr.status === 200){ | |
var employees = JSON.parse(xhr.responseText); | |
resolve(employees) | |
} else { | |
reject(this.statusText); | |
} | |
} | |
}; | |
}); | |
} | |
//var ajaxPromise = getJSON('../data/employees.json'); | |
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(unorderedList) { | |
document.getElementById('employeeList').innerHTML = unorderedList; | |
} | |
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