0

I am calling a local json file using fetch and aync and await, but when I call this all I see in the console is the Promise pending and in it showing the state as fulfilled and not the json data.

The code is

$(document).ready(() => {
    const jData = ReturnJSONData();
    
    console.log(jData);
});


async function ReturnJSONData() {
    const data = await fetch("../TreeListData.json");
    const ds = await data.json();
    return ds;
}

In the async function the returning ds has the json in it

Chris
  • 2,953
  • 10
  • 48
  • 118

2 Answers2

3

async functions always return promises. If you need to interact with the value inside that promise, either call .then on that promise:

$(document).ready(() => {
    const promise = ReturnJSONData();
    promise.then(jData => {
      console.log(jData);
    });
});

or put your code in an async function and await the promise.

$(document).ready(async () => {
    const jData = await ReturnJSONData();
    console.log(jData);
});
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
2

Your call to fetch is async, which means you need to await it.

$(document).ready(async () => {
    const jData = await ReturnJSONData();
    
    console.log(jData);
});


async function ReturnJSONData() {
    const data = await fetch("../TreeListData.json");
    const ds = await data.json();
    return ds;
}

To demo this working with a dummy async call:

$(document).ready( async ()=>{
  await dummyPromise();
  console.log("done")
})

const dummyPromise = async () => new Promise(resolve => setTimeout(resolve,2000))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Jamiec
  • 133,658
  • 13
  • 134
  • 193