Skip to content

Instantly share code, notes, and snippets.

@kypflug
Last active October 30, 2015 20:39
Show Gist options
  • Save kypflug/ea19ed5faf0cd07c2141 to your computer and use it in GitHub Desktop.
Save kypflug/ea19ed5faf0cd07c2141 to your computer and use it in GitHub Desktop.
// ES6 code, without async/await
// 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);
});
@just-boris
Copy link

You just can't use the Promises. Why not to write httpGetJson as:

function httpGetJson(url) {
    // check if the URL looks like a JSON file and call httpGet.
    var regex = /\.(json)$/i;
    if (regex.test(url)) {
        return httpGet(url);
    } else {
        return Promise.reject(Error('Bad File Format'));
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment