Skip to content
This repository has been archived by the owner on Jan 24, 2023. It is now read-only.

Commit

Permalink
Add Promise sample ajax call 🔄
Browse files Browse the repository at this point in the history
  • Loading branch information
sicktastic committed Jun 20, 2016
1 parent 589997f commit 1d6da0b
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions promises/widget.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
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) {
var employees = JSON.parse(xhr.responseText);
resolve(employees)
} else {
reject(this.statusText);
}
};

});
}

function generateListItems(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('some_data.json')
.then(generateListItems)
.then(generateUnorderedList)
.then(addEmployeesToPage)
.catch(function(e) {
console.log(e):
})

0 comments on commit 1d6da0b

Please sign in to comment.