Last active
October 7, 2017 11:19
-
-
Save bluerid/5c052e7b445a32784e3f11257b99de91 to your computer and use it in GitHub Desktop.
XHR Example Request / Async Callback
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
<html> | |
<head> | |
<title>Blurb Card</title> | |
<style> | |
body{ | |
background-color: #ccc; | |
} | |
p, ul, blockquote { | |
color: #333; | |
padding: 0 0 0 5px; | |
} | |
#content{ | |
max-width: 900px; | |
margin: 0 auto; | |
} | |
</style> | |
<script> | |
var url = 'https://api.github.com/search/users?page=1&type=Users&q=bluerid'; | |
function request( url, callback ) { | |
const xhr = new XMLHttpRequest(); | |
xhr.timeout = 2000; | |
xhr.onreadystatechange = function(e) { | |
if( xhr.readyState === 4 ){ | |
if( xhr.status === 200 ) { console.log(xhr.status) | |
callback(null, xhr.response); | |
} else { | |
callback(xhr.status, null); | |
} | |
} | |
}; | |
xhr.ontimeout = function() { | |
console.log('Timeout'); | |
}; | |
xhr.open('get', url, true); | |
xhr.send(); | |
} | |
function handleUsersList( error, users ) { | |
if(error) throw error; | |
const usersList = JSON.parse(users).items; | |
if ( usersList instanceof Array) { | |
usersList.forEach( function( user ) { | |
if( user.hasOwnProperty('repos_url') ) { | |
console.log(user.repos_url) | |
request( user.repos_url, handleReposList ); | |
} | |
}); | |
}; | |
}; | |
function handleReposList(err, repos){ | |
if (err) throw err | |
console.log('My very few repos', repos) | |
} | |
try { | |
request( url, handleUsersList ); | |
} catch( err ) { | |
console.error( err ); | |
} | |
</script> | |
</head> | |
<body> | |
<div id="content"> | |
<blockquote>Remember that in these examples the important part is not what the end result of the code is. Instead your goal should be to understand the differences of the approaches and how you can leverage them for your development.</blockquote> | |
<p>You can save a reference of a function in a variable when using JavaScript. Then you can use them as arguments of another function to execute later. This is our “callback”.</p> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment