Skip to content

Instantly share code, notes, and snippets.

@JoeShep
Created February 25, 2016 16:23
Show Gist options
  • Save JoeShep/4f161f9178db3ec82a7c to your computer and use it in GitHub Desktop.
Save JoeShep/4f161f9178db3ec82a7c to your computer and use it in GitHub Desktop.
Promises / Callbacks Comparison
var CarLot = (function () {
var inventory = [];
var fillInventory = function(data) {
data.cars.forEach(function(element){
inventory.push(element)
});
}
return {
getInventory: function () {
return inventory
},
loadInventory: function (callback) {
var inventoryLoader = new XMLHttpRequest();
inventoryLoader.open("GET", "inventory.json");
inventoryLoader.send();
inventoryLoader.addEventListener("load", function () {
var data = JSON.parse(this.responseText);
fillInventory(data);
callback(inventory);
});
}
};
})();
var CarLot = (function () {
var inventory = [];
var fillInventory = function(data) {
data.cars.forEach(function(element){
inventory.push(element)
});
}
return {
getInventory: function () {
return inventory
},
loadInventory: function (url) { //<--- Takes an arg. of the url of the JSON file instead of a callback function.
return new Promise( function (resolve, reject) { // loadInventory now just returns a Promise object
var request = new XMLHttpRequest();
request.onload = function () {
if (this.status === 200) {
// Success
var data = JSON.parse(this.responseText);
fillInventory(data);
resolve(inventory); // Broadcasts inventory for our .then to listen for, instead of running a callback
} else {
// Something went wrong (404 etc.)
reject(new Error(this.statusText));
}
};
request.onerror = function () {
reject(new Error(
'XMLHttpRequest Error: '+ this.statusText));
};
request.open('GET', url);
request.send();
});
}
}
})();
// CALLBACK VERSION
// Load the inventory and send a callback function to be
// invoked after the process is complete
CarLot.loadInventory(populatePage); //<----populatePage gets sent to loadInventory as a callback
//PROMISES VERSION
//The Promises Way puts the callback responsibility on the caller
CarLot.loadInventory('inventory.json')
.then( //<--- Listens for Promise to broadcast 'resolve' or 'reject' events
function (cars) { //<---- Runs is Promise is resolved (successful)
populatePage(cars) //<---populatePage called after Promise is resolved.
},
function (reason) { //<--- Runs if Promise is rejected
console.error('Something went wrong', reason);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment