Can someone please explain in simple terms, how to return data from fetch? I can console.log the information with ease, but I cannot for the life of me get the JSON data that fetch is returning into a variable so I can manipulate the data.
function apiCall(path,options){
fetch(path,options)
.then(response => response.json())
.then(data => console.log(data));
}
apiCall("http://localhost:3000/getJSON",{});
Works, and logs the JSON as expected.
The docs state that :
"If a handler function returns a value, the promise returned by .then gets resolved with the returned value as its value."
So, I should be able to return a value from the .then handler function and have it resolve to a value, correct? If I attempt to return a value in:
function apiCall(path,options){
fetch(path,options)
.then(response => response.json())
.then((data) => {
console.log(data)
return data;
});
}
let foo = apiCall("http://localhost:3000/getJSON",{});
console.log(foo);
This doesnt work, it correctly logs the data inside the .then on the response.json() function, but doesn't return the value to me in a useable way. Am I fundamentally misunderstanding the way that promises are resolved?