0

So, I want to use fetched data from an API in my app, but I cannot store the fetched data outside of async function getapi(), but if I use all other functions while staying inside that getapi() function, they are working fine but I want to store the fetched data outside of that function to make my code more readable and clear.

var mdata;
const api_url = "https://api.jsonbin.io/b/602998b0f460fe73a1967fe0";
async function getapi(url) {

    const response = await fetch(url);
    data = await response.json();
    mdata = data;

}
getapi(api_url);
console.log(mdata);

Output of this JS

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Samiatrix
  • 3
  • 4

1 Answers1

0

In the way you're executing your code you're not waiting for the async function to finish.

Your code should look something like this.

Learn more about promises here link

var mdata;
const api_url = "https://api.jsonbin.io/b/602998b0f460fe73a1967fe0";
async function getapi(url) {

    const response = await fetch(url);
    data = await response.json();
    mdata = data;

}
getapi(api_url).then( function(){
  console.log(mdata);
  }
);
Joaquín
  • 1,116
  • 1
  • 10
  • 26
  • No, I think you didn't got my point, I want to store the fetched data in my mdata variable which is a global variable and I want to use pass mdata variable(fetched data) to some other function to do some work like access data. – Samiatrix Feb 18 '21 at 12:34