Skip to content

Instantly share code, notes, and snippets.

@amikitevich
Created December 17, 2017 21:43
Show Gist options
  • Save amikitevich/79bb73572965cc3c515773d0d15310bd to your computer and use it in GitHub Desktop.
Save amikitevich/79bb73572965cc3c515773d0d15310bd to your computer and use it in GitHub Desktop.
XHR get by Promise and async
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