Created
February 20, 2020 23:12
-
-
Save brunotdantas/50f452bc9437371f7e528226d9662c2e to your computer and use it in GitHub Desktop.
Ajax example with promises
This file contains hidden or 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
// 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); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use Axios to an enhanced request
https://github.com/axios/axios