Skip to content

Instantly share code, notes, and snippets.

@brunotdantas
Created February 20, 2020 23:12
Show Gist options
  • Save brunotdantas/50f452bc9437371f7e528226d9662c2e to your computer and use it in GitHub Desktop.
Save brunotdantas/50f452bc9437371f7e528226d9662c2e to your computer and use it in GitHub Desktop.
Ajax example with promises
// Use this solution when we need to do an action when the request is finished
var myPromise = function(){
return new Promise(function(resolve,reject){
var xhr = new XMLHttpRequest();
xhr.open('GET','https://api.github.com/users/brunotdantas');
xhr.send(null); // if you have any parameters to complement the request
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
//request finished and response is ready
if (xhr.status === 200){
resolve(JSON.parse(xhr.responseText)); // returned value
}else{
reject('Request Error');
}
}
}
})
}
myPromise()
.then(function(response){
console.log(response);
})
.catch(function(error){
console.warn(error);
})
@brunotdantas
Copy link
Author

brunotdantas commented Feb 20, 2020

Use Axios to an enhanced request
https://github.com/axios/axios

axios.get('https://api.guthub.com/users/brunotdantas')
    .then(function(response){
        console.log(response);
    })
    .catch(function(error){
        console.warn(error);
    })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment