1

I am using fetch() to import a json file called map.json, but I can't seem to access it. Here is my code:

export function importJSON(url) {
    return fetch(url)
        .then(r => r.json())
        .then(data => {
            return data;
        });

}

then I call the function to a variable called json, and log it to the console:

const json = importJSON('../src/JSON/map.json');
console.log(json);

When I log it though, it doesn't just say what my JSON file is, it just shows the Promise and I don't know how to access it, it's under [[PromiseResult]]:

Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object
map: {platform: {…}}
__proto__: Object

And under Promise is the JSON (as you can see the map and platform). How do I access the JSON?

1 Answers1

0

You can do this with an async IIFE (immediately invoked function expression):

(async () => {
    const json = await importJSON('../src/JSON/map.json');
})();
Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
Or Assayag
  • 5,662
  • 13
  • 57
  • 93