Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
When you want a promisified version of jQuery's $.getJSON function
/*
* Usage:
* getJSON("https://jsonplaceholder.typicode.com/comments", { postId: 1})
* .then(data => {
* console.log(data);
* });
*/
function getJSON(url, qs_params) {
function buildQueryString(params) {
return Object.entries(params).map(d => `${d[0]}=${d[1]}`).join('&');
}
return new Promise((resolve, reject) => {
const qs = qs_params ? '?' + buildQueryString(qs_params) : '';
const xhr = new XMLHttpRequest();
xhr.open('GET', `${url}${qs}`);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) {
resolve(JSON.parse(xhr.responseText));
} else {
resolve(xhr.responseText);
}
};
xhr.onerror = () => reject(xhr.statusText);
xhr.send();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.