Skip to content

Instantly share code, notes, and snippets.

@nishant8BITS
Created January 17, 2018 13:55
Show Gist options
  • Save nishant8BITS/4864a99d340dfb333730fc183cef8cb9 to your computer and use it in GitHub Desktop.
Save nishant8BITS/4864a99d340dfb333730fc183cef8cb9 to your computer and use it in GitHub Desktop.
// From callback to async/await
// 1. Callback
const makeHttpRequest = (url, methodType, callback) => {
const xhr = XMLHttpRequest();
xhr.open(methodType, url, true);
xhr.onreadystatechange = () =>{
if(xhr.readyState === 4 && xhr.status === 200){
callback(xhr.responseText);
}
}
xhr.send();
}
const getLogin(response) =>{
console.log(JSON.parse(response));
}
const url = 'https://api.github.com/users/nishant8BITS';
makeHttpRequest(url, 'GET', getLogin);
// 2. Generators
function* getUser(username){
const uri = `https://api.github.com/users/${username}`;
const response = yield fetch(uri);
const parsedResponse = yield response.json();
console.log(parsedResponse);
}
getUser('nishant8BITS');
// 3. Using async/await
const getUser = async (username) =>{
const uri = 'https://api.github.com/users/' + username
const response = await fetch(uri);
const parsedResponse = await response.json();
console.log(parsedResponse);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment