Created
October 13, 2018 17:27
-
-
Save williaanlopes/e8d9d8f2486c49b24c0feae1763c792e to your computer and use it in GitHub Desktop.
Making requests with pure Javascript and promise (Fazendo requisições com Javascript puro e promise)
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
// promise example | |
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(); | |
}); | |
} // promise example | |
// promise usage | |
get('https://jsonplaceholder.typicode.com/comments').then(function(response) { | |
console.log("Success!", response); // show data | |
}, function(error) { | |
console.error("Failed!", error); // show error | |
}); // promise usage |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment