Skip to content

Instantly share code, notes, and snippets.

@kypflug
Last active Oct 30, 2015
Embed
What would you like to do?
// 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

This comment has been minimized.

Copy link

@just-boris just-boris commented Oct 30, 2015

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