Last active
August 29, 2015 14:07
-
-
Save roman01la/b0d123ee2e795f3207d6 to your computer and use it in GitHub Desktop.
Fetch.js
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
var fetch = function (url) { | |
return new Promise(function (resolve, reject) { | |
var xhr = new XMLHttpRequest(); | |
xhr.open('GET', url); | |
xhr.onload = function() { | |
if (xhr.status === 200) { | |
resolve(xhr); | |
} else { | |
reject(xhr.status); | |
} | |
}; | |
xhr.send(); | |
}); | |
}; | |
/* Usage */ | |
fetch('/') | |
.then(function (body) { return body.responseText; }) | |
.then(function (str) { console.log(str); }) | |
.catch(function (err) { console.log(err); }); | |
/* With ES7 async/await */ | |
(async function() { | |
var users = await fetch('/users'); | |
var user = await fetch('/users/' + users[0].id); | |
console.log(user); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment