Skip to content

Instantly share code, notes, and snippets.

@coryhouse
Last active October 15, 2017 13:23
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 coryhouse/761e51597f209fbaa6507dcc3ece0128 to your computer and use it in GitHub Desktop.
Save coryhouse/761e51597f209fbaa6507dcc3ece0128 to your computer and use it in GitHub Desktop.
Callback example
getPosts(function(error, posts) {
if (error) {
console.log(error);
} else {
console.log(posts.length);
}
});
function getPosts(callback) {
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
callback(null, xhr.response);
}
}
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts");
try {
xhr.send();
} catch (error) {
callback(error);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment