Execute an asynchronous function in Javascript, then output the returned data to the console

Is there a way to effectively handle the data returned from an async function?

example: JS FILE:

   async function getData(){
      try {
         $.getJSON('./data.json', (data) => {
            return data;
         });
      } catch(error) {
         console.log("error" + error);
      } finally {
         console.log('done');
      }
   }

   console.log(getData());

JSON FILE:

{
   "stuff": {
      "First": {
         "FirstA": {
            "year": [2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017],
            "Categories": ["Suspension", "Electrical", "Performance", "Motor"]
         },
         "FirstB": {
            "year": [2007, 2008, 2009, 2010, 2011, 2012],
            "Categories": ["Suspension", "Electrical", "Performance", "Motor"]
         }
      },
      "Second": {
         "SecondA": {
            "year": [2002, 2003, 2004, 2005, 2006],
            "Categories": ["Suspension", "Electrical", "Performance", "Motor"]
         },
         "SecondB": {
            "year": [2007, 2008, 2009, 2010, 2011, 2012],
            "Categories": ["Suspension", "Electrical", "Performance", "Motor"]
         }
      }
   }
}

How can one get complete access to all the information in the JSON file and manipulate it accordingly? For instance, extracting "First" and "Second" and appending them to a div. How about "FirstA" and "FirstB", "SecondA" and "SecondB"... and so forth?

Currently, Promise {: undefined} is what I am getting.

Any assistance on this matter would be highly appreciated.

---------UPDATE---------

While running the console log within the function reveals the json data, the challenge is accessing the data externally.

Serge

Answer №1

There are two key points to consider:

  1. In order to set the resolution value of the promise generated by the async function, you need to include a return statement within the actual async function and not just within a callback such as getJSON.

  2. To synchronize with and obtain the resolution value of an async function, you must either use await or consume its promise using methods like then.

For point #1, you can modify your code to return the result of awaiting getJSON:

async function getData() {
    try {
        return await $.getJSON('./data.json').promise();
    }
    catch (error) {
        console.log("error" + error);
    }
    finally {
        console.log('done');
    }
}

Regarding point #2, you can either utilize await when handling the function directly or use then when consuming the promise:

console.log(await getData());

...or alternatively use then:

getData().then(data => {
    console.log(data);
});

Furthermore, it's crucial to note that your current implementation of getData masks errors by transforming them into resolutions with the value of undefined. To avoid this behavior, ensure that errors are properly propagated:

catch (error) {
    console.log("error" + error);
    throw error;
}

Make sure that any code utilizing getData effectively handles or propagates errors to prevent "unhandled rejection" errors.


In response to your query about accessing the content from the JSON file outside the function:

how would I access the "stuff" in the json file from the log outside the function?

The resolved value of getData is the object defined in the JSON file (after parsing). Therefore, you can simply use .stuff to access it:

// Inside an `async` function
console.log((await getData()).stuff);

// Alternatively, using `then`:
getData().then(data => {
    console.log(data.stuff);
});

Answer №2

This is the method I often use. First, create an async function like this:

private logToConsoleAsync = async (message: string, data?: any) => {
    await new Promise((resolve) => setTimeout(resolve, 0)).then(() => console.info(message, data));
};

Then, simply call this function within your own async function when you need to log something:

await this.logToConsoleAsync('This is my message', myData);

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

Tips on parsing JSON data with Python

I am currently working with a module that provides data in the following format: j = ("{u'auth_user': {u'first_name': u'a', u'last_name': u'b', u'uid': u'x', u'timezone_offset&apos ...

While attempting to read and write to a JSON file, I encountered the error: "raise JSONDecodeError("Expecting value", s, err.value) from None"

Hey there! I've been working on a project where I need to read from a json file with a dictionary structure and update it by adding more entries. However, I'm encountering an error that I can't seem to figure out. I've spent 10 hours tr ...

AngularJS: intercepting custom 404 errors - handling responses containing URLs

Within my application, I have implemented an interceptor to handle any HTTP response errors. Here is a snippet of how it looks: var response = function(response) { if(response.config.url.indexOf('?page=') > -1) { skipException = true; ...

Enhancing the protection against JSON injection in Java

I have been trying to sanitize JSON data using the code below, but I am still encountering JSON injection issues when scanning with Fortify. Can someone please assist me in identifying the problem? I have looked for similar questions, but none of the solut ...

Maintain the selected bootstrap tab even after the page is refreshed, even when the content is loaded dynamically

I am currently facing an issue with loading tabs using Angular. Whenever a tab is clicked, the id is saved to localStorage. Now, I want to programmatically click on the same tab using jQuery when the page refreshes. However, since the DOM element for the ...

Implementing the sorting feature in Angular JS to properly align sub sections with their correct parent sections

I'm facing an issue with the functionality of my sample code. Users can add sections and subsections within those sections, which are sortable using ui-sortable. However, after sorting the items, if I try to add a new sub-section to Section 2, it wron ...

Is it possible to modify the host header within an Angular app?

I'm experiencing a vulnerability issue and to resolve it, I need to utilize SERVER_NAME instead of the Host header. Is it possible to accomplish this using Angular? ...

What is preventing me from displaying the results on the webpage?

Currently, I am utilizing Express alongside SQLite and SQLite3 modules. However, upon running the server, the data fails to display on the initial request. It is only after a page refresh that the data finally appears. I attempted a potential solution by ...

Leverage the power of Angular's $http module in conjunction with Django's urlpatterns to fetch

I am attempting to send a $http GET request to a Django URL pattern in order to retrieve a .json file. Is it possible to use urlpatterns to return a file instead of a view? Is this scenario achievable, or are there limitations preventing this from working ...

PNG file is not displayed on React TSX page despite absence of any errors

I've implemented this initial design template from GitHub (https://github.com/vikpe/react-webpack-typescript-starter). Additionally, I'm utilizing react-bootstrap and have a container that includes a backgroundImage. const heroImage = require(&q ...

Creating a customized image modal in ReactJS that incorporates a dynamic slideshow feature using the

I am attempting to incorporate an image lightbox into my React application: https://www.w3schools.com/howto/howto_js_lightbox.asp Here is the link to the CodeSandbox where I have tried implementing it: https://codesandbox.io/s/reactjs-practice-vbxwt ...

When I attempt to read a JSON file using JSON SERDE, I am only fetching a single row

JSON Data: [{ "liked": "true", "user_id": "101", "video_end_type": "3", "minutes_played": "3", "video_id": "101", "geo_cd": "AP", "channel_id": "11", "creator_id": "101", "timestamp": "07/05/2019 01:36:35", "disliked": "true" }, { "lik ...

Choose only one option from the dropdown menu at a time within the specified div

I attempted to utilize the "setSelected" option on my multiselect feature, but I noticed that it does not function with div elements (at least I could not make it work myself). I am endeavoring to create two synchronized multiselects using this example: b ...

Displaying JSON data from the API on a webpage within a NodeJS weather application

Currently, I am in the process of developing a weather application using NodeJS. I have successfully retrieved JSON formatted data from the weather site's API. Nonetheless, I am perplexed about how to transmit this data to the application. Below is a ...

Effectively implementing an event observer for dynamically loaded content

I want to set up an event listener that triggers when any of the Bootstrap 3 accordions within or potentially within "#myDiv" are activated. This snippet works: $('#myDiv').on('shown.bs.collapse', function () { //code here }); Howeve ...

Exploring the applications of the `this` keyword within a jQuery-based JavaScript object

Recently, there has been a challenge in creating a JavaScript object with the specific structure outlined below: function colorDiv(div){ this.div=div; this.div.bind("click",this.changeColor) this.changeColor(){ this.div.css(" ...

What is the process for accessing and implementing system-wide proxy settings for my Electron application?

Currently, I am working on a webpage that has similarities to the one found in this link: I am looking for guidance on how to programmatically set a system-wide proxy in my application, as well as how to configure them manually if users prefer that option ...

What seems to be the issue with this Discord.js kick command code? It's not

Okay, so I'm in the process of creating a kick command for my Discord bot. The issue I'm encountering is that when no reason is specified or if a user is not mentioned to be kicked, the bot responds correctly but does not actually kick the user. ...

What is the best way to pass a variable and its corresponding state-updating function as a prop in a React component?

Considering I have a variable defined as follows: const [APIKey, setAPIKey] = useState([]) Is it possible to group these together into a single variable and then pass it as a prop? const passAPI = {APIKey, setAPIKey} Here is my approach to passing it alo ...

Encountering a null pointer error when trying to map JSON fields to a POJO

I have a JSON string as shown below. I am trying to map only the TYPE and UN_NUM fields from the SEGMENT object to a POJO, but my code is returning null values. test.json { "TEST": { "NAME": "PART_TRAN", "VERSION": "9.0", "ID" ...