Using axios with async/await to handle unresolved promises in Javascript

I'm facing a challenge with a piece of code I've been working on. Despite my efforts to find a solution online, I haven't had any success so far. Here is the code snippet in question:

   const fetchSidebarData = async () => {
      let dataArray = []
      await axios.get('https://jsonplaceholder.typicode.com/posts').then(res => {
        console.log('res1', res)
        dataArray = res.data
      }).catch(err => console.log(err))
      console.log('dataArray', dataArray)
      return dataArray
    }

When I call this function like this:

 const retrievedData = fetchSidebarData()
    console.log('retrievedData', retrievedData)

The output in the console shows:

retrievedData Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Array(100)

How can I store the PromiseResult in a variable? Any help would be greatly appreciated!

Answer №1

Make sure to allow the promise to complete before trying to access the output:

const executeFunction = await loadPageContent()

Answer №2

fetchDataFromSideBar is an async function that returns a Promise, so you must wait for it to complete.

const sidebarData = await fetchDataFromSideBar();

Alternatively, you can use the .then() method.

Answer №3

Retrieve information directly from the fetchMenuData function:

const fetchMenuData = async () => {
  const {info} = await axios.get('https://jsonplaceholder.typicode.com/posts')
  return info
}

const menuInfo = await fetchMenuData()

Answer №4

Don't overlook this important keyword in your code.

const fetchData = await fetchUserData()
console.log('fetchData', fetchData)

original article: video reference: https://www.youtube.com/watch?v=abc123

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

Utilizing the power of Angular 4 in combination with mailgun

I need assistance with setting up an email form on my website using Angular 4 and Mailgun as the mail service. I have a method in my mail service file to send messages, but I keep encountering a Bad Request error stating that 'from' is not presen ...

Exploring Material UI: Understanding the contrast in functionalities between incorporating the Icon component and the Material Icons node

I am looking to incorporate Material Icons into my application. I have come across two methods provided by Material UI for adding the same icon to my site: Using the <Icon /> component, which is part of the @material-ui/core package: <!-- Add t ...

Error encountered: WebGL Type error in Three.js

Currently working on a small music visualizer project using WebGL and Three.js with the help of the ThreeAudio.js library. Everything seems to be running smoothly, but I've encountered an error that I'm keen on resolving: "Uncaught Type Error: T ...

When a new ajax function is added, the original Ajax code stops functioning

I've been working on getting the code below to function properly. It seems that when I test the code, two validation functions are working correctly. However, when I include the validateUsername() function along with the if statement in the code, ever ...

How to Determine If a String Represents an HTML Tag Using jQuery

Checking if a string is an HTML tag can be tricky. I've tried various methods found on Google, but none have been successful so far: var v = $(string).html() ? 1 : 0; --or---------------------------------------------- var htmlExpr = new RegExp("/^( ...

In jQuery, conditionally nest divs within another div based on a specific requirement

There is a container with multiple nested elements that need to be rearranged based on the value of their custom attribute. The goal is to reorder those elements at the end of the container if their 'data-keep-down' attribute is set to true, usin ...

How does the interaction between Express and Angular for routing in the MEAN Stack function?

Currently, I am utilizing Express static to direct to the public directory. //app.js app.use(express.static( __dirname + '/public')); I am looking for a way to have most of the UI routing done by AngularJS. However, it seems that it only works ...

Instructions for copying a vuedraggable item into the nested children list of its sibling element

Visit this link for more information Everything seems to be working with the pull operation, but as soon as I switch the pull prop from 'true' to 'clone', an error pops up. An issue occurred: NotFoundError - Failed to execute 'i ...

The calendar loses its focus when I try to interact with it

One issue I have encountered is that when I click on the input field to display the Calendar component, and then click outside of it to hide it, everything works smoothly. However, the problem arises when I click directly on the icon (Calendar component) i ...

Creating functional dropdown menus with popperjs in the latest Bootstrap version 5

Currently, I am attempting to implement dropdown menus in Bootstrap 5. According to my research, this feature requires Popper.js integration, but I am uncertain of the correct way to include it in my Laravel project that utilizes Laravel Mix. I have made ...

Data on global map routes displayed in highcharts react

After reviewing the react highmaps documentation, it appears that they have saved the map data in a hardcoded manner. Take a look at Link 1 Check out Link 2 In various tutorials, I noticed that the data is retrieved from high maps itself by passing a ke ...

Steps for importing a json file into Chrome

Inside my file named data.json, there is a JSON object structure: { "k": : "..some object...", "a": [ "...", "bbb" ] } When working with Node.js, I can easily import this data into a variable using: let data = require("./data.json"); However, how can I ...

Using SWR, retrieve data in client components consistently for each request in a Next.js version 13.3 environment

I recently upgraded to Next.js 13.3 with the app dir set up. I have a simple component that displays the current date. However, it only updates the date once and then doesn't update again until I rebuild the app. In Next.js 12, the date would update w ...

Spinner displayed upon task completion

Currently, I am developing a project using Spring Boot. I would like to display a spinner on my page to indicate that a task involving heavy calculations is in progress. Even though the page may take up to 5 minutes to load, my spinner only appears for t ...

Exploring the concepts of closure and scope

It seems that the function inResult always returns false and the loop is not being executed, probably due to a lack of understanding of closures. However, I can confirm that the result variable contains the correct properties. function hasId() {return ...

Error when handling JSONP: Unexpected token colon in SyntaxError

Encountering a similar issue to the ones discussed in this JSON Uncaught SyntaxError thread and this JSONP Unexpected Token error thread. I attempted to fetch Divvy data through a JSONP call to avoid using a server for my simple front-end application. $. ...

Exploring nested arrays of objects and applying value constraints

Is there a way to iterate through an array and display only 5 items at once, with the option to call a function on click that will add another 20 items? I have an object structured like this: let someObject = [ { data: [ { id: 123, ...

Is it possible to maintain inline style modifications when the dispatch event is triggered?

I am encountering an issue with inline style changes that are reset once my dispatch function is completed. Even though the rest of my component's functionality is working fine (the counter continues to run), the state is being re-rendered. Here is a ...

What causes an error when attempting to add a new user to the database?

Currently, I am delving into the world of Mongodb. To kick things off, I initiated by executing npm install --save mongoose uuid within the confines of Terminal. The primary objective of my project revolves around storing user information in the database. ...

When a project sets useBuiltIns to 'usage', there is an issue with importing the library generated by Webpack

I am eager to create a versatile UI component library and bundle it with Webpack. However, I encountered an issue when trying to import it into another project that has useBuiltIns: 'usage' specified in the babelrc file. The import fails with the ...