Skip to content

Instantly share code, notes, and snippets.

@kypflug
Created September 25, 2015 23:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kypflug/36e586f7c978e9b1bec3 to your computer and use it in GitHub Desktop.
Save kypflug/36e586f7c978e9b1bec3 to your computer and use it in GitHub Desktop.
// ES7 code, with async/await
// ES7 code, with async/await
function httpGet(url) {
return new Promise(function (resolve, reject) {
// do the usual Http request
let request = new XMLHttpRequest();
request.open('GET', url);
request.onload = function () {
if (request.status == 200) {
resolve(request.response);
} else {
reject(Error(request.statusText));
}
};
request.onerror = function () {
reject(Error('Network Error'));
};
request.send();
});
}
async function httpGetJson(url) {
// check if the URL looks like a JSON file and call httpGet.
let regex = /\.(json)$/i;
if (regex.test(url)) {
// call the async function, wait for the result
return await httpGet(url);
} else {
throw Error('Bad Url Format');
}
}
httpGetJson('file.json').then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment