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

Understanding the concept of hoisting in JavaScript for global variables and functions

I've been curious about hoisting. I understand that if a global function shares the same name as a global variable, the function will overwrite the variable's name. Is this correct? Here is an example code snippet. (function() { console.log ...

Express encountering a problem while rendering a new page following a fetch request

Issue with Fetching and Rendering DataURL I have configured an HTTP fetch request from the client side to send JSON data (a dataURL from a canvas) to the server. However, I am facing an error while trying to access it on the server side and render a new p ...

Check if certain entries in the JSON object already exist by iterating through it

As I work on iterating over a JSON object to verify the existence of certain entries, my current JSON data structure is outlined below: [ { "title": "scname", "html": "<div><iframe src=/scenario/test3dx ...

Always ensure that an element remains at the bottom during the sorting process

Currently, I have a list of items with an integer attribute that aids in sorting the list. However, I am looking for a way to designate specific items to always appear at the bottom of the list regardless of the sorting criteria. Is there a singular valu ...

What is the best way to implement a function that can combine multiple arrays together in C++?

Currently, I am in the process of developing a function that takes the values from another array and adds them together. The approach I am using involves storing single digits in separate arrays and then performing addition on these arrays. However, when a ...

Nested function unable to assign values to variables

I am currently working on a function in Discord.js that collects users who reacted to a message. I have managed to gather all the user IDs inside a nested function, but when trying to return the array to the caller, it does not seem to work as expected. He ...

What is the reason for the lack of data being displayed when using console.log() with a map object?

I currently have pet information stored in a MongoDB object like so: { "_id" : ObjectId("0000439359317900131f111"), "name" : "Travis", "description" : "Travis is a support animal", ...

Achieving dynamic height in a parent div with a sticky header using mui-datatables

Here are the settings I've configured for my mui-datatables: const options = { responsive: "standard", pagination: false, tableBodyHeight: '80vh', }; return ( <MUIDataTable title={"ACME Employee ...

Is it possible to utilize the Zoho Inventory API to enable tracking of both inventory and serial numbers for items?

I'm currently utilizing the Zoho Inventory API to modify an item, but it appears that the inventory tracking details are not being reflected in the API. Any suggestions for a workaround, or do I simply have to wait for V2 of the API? ...

What is the method for implementing an 'AND' condition in Firebase or its equivalent?

I have a query requirement where I am looking to display only specific data by using an 'AND' statement or its equivalent. To better explain, I am referencing the example given in the Firebase Documentation. // Find all dinosaurs whose height is ...

Passing models in JSON via AJAX is a common practice in MVC 4

.I am attempting to send my view model via ajax using the following code: var val = Json.Encode(Model); var check = @Html.Raw(val); $("#stats").click(function (e) { e.preventDefault(); console.debug(JSON.stringify(check)); $.ajax({ ur ...

Button click not triggering JQuery click event

$(document).ready(function () { $('#btnApplyFilter').click(function () { alert("JQuery is not running!"); }); }); Why is the above function not working when the button is clicked? Here is the code for my button : ...

Error encountered while parsing JSON data from LocalStorage

Storing an object in localStorage can sometimes lead to unexpected errors. Take this example: function onExit(){ localStorage.setItem("my_object","'" + JSON.stringify(object) + "'"); } When retrieving this data from localStorage, it may loo ...

Is it possible to transform a reference to a React Component into JSON format?

I am looking to serialize the state of a React component into JSON format and save it in a database. Here is the current structure of my code: const [exampleState, setExampleState] = useState([ { componentName: "Test component", co ...

The JavaScript require() function appears to be malfunctioning

Why am I encountering an error when trying to import a valid node_module? <script > var Twit = require('twit'); </script> Error: Uncaught ReferenceError: require is not defined I am puzzled as to why the require() function wor ...

When using Node.js, you may encounter the error message: "TypeError: brevo.ApiClient is not a constructor

My goal is to set up an automatic email sending system that, upon receiving details like name and email, will send a confirmation email to the provided email address with the message "subscribed." I've been working on this task for about 7 hours strai ...

What is the best way to locate elements with the term "download" in them using Selenium's x-path feature?

I'm currently utilizing Selenium for web scraping purposes and I am in need of a way to identify all clickable elements that contain the word "download" (regardless of capitalization) within their link text, button text, element ID, element class, or ...

How does the Rx subscribe function maintain its context without the need to explicitly pass it along

Currently, I am utilizing Rx with Angular2 and making use of the Subscribe method. What intrigues me is that the callbacks of the method are able to retain the context of the component (or class) that initiated it without needing any explicit reference pas ...

Executing Grunt: Setting up a dual Connect and Express server to operate on one port

I'm still fairly new to Grunt and I've been wondering if it's possible to run both servers on the same port simultaneously. I seem to be encountering some issues with this setup, most likely stemming from the Grunt file. I am utilizing grun ...

Is it Possible to Load JSON Data as Columns Instead of Rows in Datatables?

My understanding is that typically, with Jsons and Datatables, each record is loaded as a row of data for the table. I am looking for a way to load json data as columns instead of rows in DataTables. However, I have not found a suitable method to achieve ...