I'm trying to get JSON saved into a variable, but it seems I don't understand everything here. I get JSON show up in console a once the way I like, but after I try to call it again later it only returns promise. How can I get JSON saved into a variable, so I could use objects in JSON later?
var jsondata = fetch(url).then(
function(u){ return u.json();}
).then(
function(json){
console.log(json);
}
)
console.log(jsondata);
The fetch API is Promise based and will always return a new Promise either resolved or rejected. You have multiple options to return the result.
async function getData(url) {
const response = await fetch(url);
return response.json();
}
const data = await getData(url);
console.log({ data })
function getData(url, cb) {
fetch(url)
.then(response => response.json())
.then(result => cb(result));
}
getData(url, (data) => console.log({ data }))
You can create a separate function outside the fetch function to deal with json data like in below code the fetch function is passing the complete json object to another function called "data_function" we can proceed and work with JSON object in through this "data_function".
//fetch function
fetch(url).then(
function(u){ return u.json();}
).then(
function(json){
data_function(json); //calling and passing json to another function data_function
}
)
//another functions
function data_function(data){
alert(data.length);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With