const xhr = new XMLHttpRequest()
xhr.open('GET', requestURL)
xhr.onload = () => {
const data = (JSON.parse(xhr.response))
}
xhr.send()
Is it even possible to return "const data". I need use that json anyway
const xhr = new XMLHttpRequest()
xhr.open('GET', requestURL)
xhr.onload = () => {
const data = (JSON.parse(xhr.response))
}
xhr.send()
Is it even possible to return "const data". I need use that json anyway
Return the value via a promise. Wrap the code in a promise and return the promise.
function httpCall(){
return new Promise((resolve, reject){
const xhr = new XMLHttpRequest()
xhr.open('GET', requestURL)
xhr.onload = () => {
if(xhr.status == 200) {
const data = (JSON.parse(xhr.response));
resolve(data);
} else {
reject("Failure to fetch data.");
}
}
xhr.send();
});
}
And call the function via a async / await call.
async function makeHttpCall(){
const data = await httpCall();
console.log(data);
}