Created
July 16, 2020 20:49
-
-
Save connoro7/d07287b29d1e661c55ad0d66c8363687 to your computer and use it in GitHub Desktop.
Callbacks vs. Promises
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
// 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