What is the method for retrieving the JSON data with the fetch API?

I'm currently stuck trying to access a JSON file called map.json using fetch(). Here's my code snippet:

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

}

Then I assign the result of the function call to a variable named json and log it to the console:

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

However, when I log it, instead of displaying the actual JSON content, it shows a Promise with [[PromiseResult]] that contains the JSON data. But I'm unsure how to access it properly:

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

Beneath the Promise section is the actual JSON (including map and platform keys/values). How can I correctly access this JSON data?

Answer №1

One way to achieve this is by using an async IIFE (immediately invoked function expression):

(async () => {
    const data = await fetchJSONData('../src/data/file.json');
})();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensure that the jQuery datepicker is set with a maximum range of 365 days between the two input fields

Setting Up jQuery Datepicker Inputs I have implemented two jQuery datepicker inputs with default settings as shown below: $("#polis_date_from").datepicker({ uiLibrary: "bootstrap4", changeYear: true, changeMonth: true, dateFormat: "yy.mm.dd", ...

"Implementing a function triggered by a change event within a concealed input

I am working with two AJAX functions. The first function takes the input from the first field, concatenates a string to it, and then updates the value of the second hidden input field. However, the second function is supposed to detect any changes in thi ...

The function setSize() is ineffective for adjusting the browser dimensions when using JavaScript in Selenium

Attempting to adjust the size of the browser window using the following JavaScript code: driver.get(url); driver.manage().window().setSize(1200,800); Encountering an error message: 'setSize is not a function\n'. Seeking assistance in r ...

Issue detected with JavaScript object attribute containing hyphens prompts troubleshooting effort

I received a JSON response in the following structure. { "_meta" : { "next-person-id" : "1001", "totalPersons" : "1000" } } Utilizing Angular's $http service, I am attempting to retrieve this data and ac ...

Is it possible to explain why running the same code in Node.js produces different results than in a browser?

When running this code snippet, there is a discrepancy between how it behaves in the browser versus nodeJs. let abc = (() => { function xyz() { this.man = "XYZ" } xyz(); this.man = "ABC"; })() console.log(man); Expected ...

Issues with jQuery show and hide functionality are not performing as expected

A dazzling animation has been created, fading in and out gracefully. With two buttons at hand $('.point li') to reveal distinct contents $("#"+classVal+" .table-cell") Nevertheless, upon clicking $('.point li'), I aspire for its conte ...

Issue with JQuery plugin functionality when utilized repeatedly on a single page

Creating a unique JQuery plugin called grid2carousel has been my recent project. The plugin is designed to transform content displayed in a Bootstrap-style grid on desktop devices into a functional carousel on smaller screens. Although the plugin function ...

Utilizing JavaScript to retrieve a JSON file from a GitHub Pages server

I'm currently working on my website hosted on GitHub pages, which only supports static websites but allows the use of JavaScript. I have a JSON file on the GitHub server that my website runs from and I need to fetch and process it using JavaScript. He ...

I am looking for a way to save my JSON dataset, which I have scraped and is in text format, to my local machine. Additionally, I am seeking guidance on how to then

Below is the code snippet for analysis purposes: response = requests.request("GET", url, headers=headers, params=querystring) print(response.text) {"@type":"imdb.api.title.ratings","id":"/title/tt0944947/","title":"Game of Thrones","titleType":"tvSer ...

Halt the Bootstrap carousel while entering text in a textarea

Is it possible to achieve this? I think so. I have created a carousel with a form inside. The form includes a textarea and a submit button. Currently, the slider does not slide if the mouse pointer is inside it, which is good. However, if the pointer is o ...

What is the best way to call another "put" action method within the same controller file?

My project revolves around the interaction of two models - User and Request. A User can create a food delivery Request, attaching tokens as rewards. Another User can then help deliver the request and claim the tokens. Within the same controller.js file, I ...

Develop a PHP and Mysql PDO application integrated with MSSQL, JSON, jQuery, and DataTables for

Presently, I am engaged in a project where I initially started working with MySQL using Xampp. However, at this point, I wish to transition to MSSQL. Although I successfully established the connection string, I am encountering an error when utilizing datat ...

What is the reason behind the ability to access the result of a redux call "immediately" by wrapping it into a promise?

Currently, we are operating in a Redux (with thunk middleware) / React environment. The piece of code below is causing some issues: onMyClick = () => { this.props.mySynchronousActionWhichWillCreateNewReducerState(); this.setState(...my state ch ...

WebStorm failing to identify Node.js functions

I recently began my journey in learning node.js and I'm currently utilizing WebStorm 11 as my preferred IDE. However, I've encountered an issue where WebStorm does not seem to recognize the writeHead method: var http = require("http"); http.cre ...

Exploring the world of data transfer with Websockets in Flutter

What is the best way to convert JSON data into websocket data in a Flutter application? StreamBuilder( stream: _channel.stream, builder: (context, snapshot) { return ListView.builder( ...

Eliminate the unnecessary blank page from the print preview by incorporating a setTimeout function to efficiently showcase the image

Having trouble with print preview in Chrome? Want to print with images inside without displaying them initially? You can use setTimeout to show the image after a delay. However, this method creates a blank page at the end. If you remove the setTimeout, th ...

Executing an event in Javascript or triggering with Jquery- the process of initiating an event once a value is sent to an input box by Javascript

How do you trigger an event when a JavaScript-passed value is entered into an input box? <!DOCTYPE html> <html> <body> <p>Type something in the text field to activate a function.</p> <input type="text" id="myInput" oninp ...

Creating a personalized dropdown menu in react-draft-wysiwyg: A step-by-step guide

I am looking to incorporate a custom dropdown menu into the toolbar section. Here is an image that shows what I want for the dropdown menu. Can this be done? <img src="https://i.imgur.com/OhYeFsL.png" alt="Dropdown menu editor"> You can view a mor ...

Ways to determine if a specific point falls within pre-set boundaries

My set of coordinates is as follows: [ -79.763635, 42.257327 ], [ -73.343723, 45.046138 ], [ -74.006183, 40.704002 ], [ -79.763635, 42.257327 ] I am looking to determine if a point with the latitude ...

I am frustrated because the csvtojson converter keeps replacing my file name with "undefined."

Despite running the csvtojson module on node.js successfully without any additional code, I encounter an issue when attempting to include it within a function. The result returns as undefined, even though the file path remains intact. Check out the JavaSc ...