Skip to content

Instantly share code, notes, and snippets.

@mertonium
Last active May 15, 2020 01:15
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mertonium/014dfc9181b44269215ecc18666a8132 to your computer and use it in GitHub Desktop.
Save mertonium/014dfc9181b44269215ecc18666a8132 to your computer and use it in GitHub Desktop.
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