-
-
Save kypflug/36e586f7c978e9b1bec3 to your computer and use it in GitHub Desktop.
// ES7 code, with async/await
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
// 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