Last active
October 15, 2017 13:23
-
-
Save coryhouse/761e51597f209fbaa6507dcc3ece0128 to your computer and use it in GitHub Desktop.
Callback example
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
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