Created
December 17, 2017 21:43
-
-
Save amikitevich/79bb73572965cc3c515773d0d15310bd to your computer and use it in GitHub Desktop.
XHR get by Promise and async
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
function bredListRequest(resolve, reject) { | |
const r = new XMLHttpRequest(); | |
r.open('GET', 'https://api.github.com', true); | |
r.onerror = (e) => reject(e, 'error'); | |
r.onload = () => resolve(r.responseText); | |
r.send(); | |
} | |
function fetchGithubIndex() { | |
return new Promise(bredListRequest); | |
} | |
function runViaPromise() { | |
fetchGithubIndex() | |
.then(result => console.log(result)) // XHR response here) | |
.catch(e => console.error(e)) | |
} | |
async function runViaAsync() { | |
try { | |
const resPromise = fetchGithubIndex(); | |
const resValue = await resPromise; | |
console.log(resPromise); // Promise here | |
console.log(resValue); // XHR response here | |
} catch (e) { | |
console.error(e); | |
} | |
} | |
const runViaArrowAsync = async () => { | |
try { | |
const resPromise = fetchGithubIndex(); | |
const resValue = await resPromise; | |
console.log(resPromise); // Promise here | |
console.log(resValue); // XHR response here | |
} catch (e) { | |
console.error(e); | |
} | |
} | |
const write = async (fetchFn = fetchGithubIndex) => document.write(await fetchFn()); | |
// runViaPromise(); | |
// runViaAsync(); | |
// runViaArrowAsync(); | |
write(fetchGithubIndex); | |
console.log('end of script'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment