Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving fetched JSON into variable

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);
like image 551
J Hightow Avatar asked Jan 27 '18 10:01

J Hightow


2 Answers

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/Await

async function getData(url) {
  const response = await fetch(url);

  return response.json();
}

const data = await getData(url);

console.log({ data })

Callback

function getData(url, cb) {
  fetch(url)
    .then(response => response.json())
    .then(result => cb(result));
}

getData(url, (data) => console.log({ data }))
like image 102
marcobiedermann Avatar answered Sep 21 '22 01:09

marcobiedermann


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); 
}
like image 37
A.Aleem11 Avatar answered Sep 20 '22 01:09

A.Aleem11