i'm trying to send this HTTP request through my function but it returns undefined no matter what
it's a very basic request and i don't understand why this is happening
if i copy and paste the URL into my browser it works and shows the desired JSON
i tried this function on my browser's console using random id and my api key and still return undefined all the same
function getSummary(id){
let url2=`https://api.spoonacular.com/recipes/${id}/summary?apiKey=${key}`;
let xhr2=new XMLHttpRequest();
xhr2.responseType='json';
xhr2.onreadystatechange=()=>{
if(xhr2.readyState==XMLHttpRequest.DONE){
return xhr2.response;
}
}
xhr2.open('GET',url2);
xhr2.send();
}
-
i include it in the url as instructed by the API's documentation, again: pasting the url in my browser's url bar returns the desired result but the http request in my function doesn'tM.KH– M.KH2020年06月23日 16:24:36 +00:00Commented Jun 23, 2020 at 16:24
1 Answer 1
You are using the return statement inside of an arrow function and it does not return out of the main function.
xhr2.onreadystatechange=()=>{
//returns out of this function ^
if(xhr2.readyState==XMLHttpRequest.DONE){
return xhr2.response;
}
}
Instead of creating a function to return the response text you need to run a function with the response text as an argument:
let url2=`https://api.spoonacular.com/recipes/${id}/summary?apiKey=${key}`;
let xhr2=new XMLHttpRequest();
xhr2.responseType='json';
xhr2.onreadystatechange=()=>{
if(xhr2.readyState==XMLHttpRequest.DONE){
//seperate function
run(xhr2.response);
}
}
xhr2.open('GET',url2);
xhr2.send();
function run(text){
console.log(text);
};