Skip to content

Instantly share code, notes, and snippets.

@connoro7
Created July 16, 2020 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save connoro7/d07287b29d1e661c55ad0d66c8363687 to your computer and use it in GitHub Desktop.
Save connoro7/d07287b29d1e661c55ad0d66c8363687 to your computer and use it in GitHub Desktop.
Callbacks vs. Promises
// GET with callbacks
function get(url, success, error) {
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status === 200) {
var result = JSON.parse(this.responseText);
success(result);
} else {
error(this.responseText);
}
}
}
ajax.open('GET', url);
ajax.send();
}
get('https://www.reddit.com/.json', function(result) {
console.log(result);
}, function(error) {
console.log(error);
});
// GET with promises
function get(url) {
return new Promise(function(resolve, reject){
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if(this.readyState === 4) {
if (this.status === 200) {
var result = JSON.parse(this.responseText);
resolve(result);
} else {
reject(this.statusText)
}
}
}
ajax.open('GET', url);
ajax.send();
});
}
get('https://www.reddit.com/.json').then(function(result) {
console.log(result);
}).catch(function(error){
console.log(error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment