Last active
May 15, 2020 01:15
-
-
Save mertonium/014dfc9181b44269215ecc18666a8132 to your computer and use it in GitHub Desktop.
When you want a promisified version of jQuery's $.getJSON function
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
/* | |
* 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