-
-
Save kypflug/ea19ed5faf0cd07c2141 to your computer and use it in GitHub Desktop.
// ES6 code, without 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
// ES6 code, without async/await | |
function httpGet(url) { | |
return new Promise(function (resolve, reject) { | |
// do the usual Http request | |
var 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(); | |
}); | |
} | |
function httpGetJson(url) { | |
return new Promise(function (resolve, reject) { | |
// check if the URL looks like a JSON file and call httpGet. | |
var regex = /\.(json)$/i; | |
if (regex.test(url)) { | |
// call the promise, wait for the result | |
resolve(httpGet(url).then(function (response) { | |
return response; | |
}, function (error) { | |
reject(error); | |
})); | |
} else { | |
reject(Error('Bad File 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
You just can't use the Promises. Why not to write httpGetJson as: