Skip to content

Instantly share code, notes, and snippets.

@djego
Last active March 28, 2019 04:17
Show Gist options
  • Save djego/a9a46ea712ea78ef2661df0ba6413567 to your computer and use it in GitHub Desktop.
Save djego/a9a46ea712ea78ef2661df0ba6413567 to your computer and use it in GitHub Desktop.
Ejercicio con promesas
let url = "https://randomuser.me/api/";
function get(url) {
// Return a new promise.
return new Promise(function(resolve, reject) {
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
resolve(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function() {
reject(Error("Network Error"));
};
// Make the request
req.send();
});
}
get(url).then(function(response) {
console.log("Success!", response);
}, function(error) {
console.error("Failed!", error);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment