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

I sought out a way to incorporate a hyperlink within the Material Data Grid

Take a look at this sample data grid for reference: here. I added an image like this: see here. However, I couldn't create a clickable link. ...

Is it possible to use Koajs without needing to include the --harmony tag?

Following the merge of iojs into Node, I assumed that I could run koajs without the need for the --harmony tag (as it would have support for generators from es6). Inside my server.js file, I have the following code: var koa = require('koa'); va ...

Skip using bootstrap-vue icons by utilizing the Webpack IgnorePlugin

After analyzing with Webpack bundle analyzer, I discovered that the icons from the bootstrap-vue package are a whopping 535kb in size. Knowing this, I've decided not to utilize them in my project. I attempted to exclude the entire package using a web ...

Error message: Component is unable to access the $store property because it is undefined

After doing extensive research and reading numerous similar questions on various platforms, I am still unable to resolve my issue. I have a component containing a login form that triggers a method to dispatch a $store action for logging in the user via fi ...

What is the reason behind React deciding to skip the final question, even though it has been accurately saved to the

A simple web application was developed to calculate risk scores by asking five questions, with additional points awarded if a checkbox is checked. Despite extensive hours spent debugging, a persistent bug remains: the final question does not appear on the ...

What is the best way to transfer a PHP string to JavaScript/JQuery for use in a function?

Within my PHP code, I have the following: $welcome = "Welcome!"; echo '<script type="text/javascript">addName();</script>'; Additionally, in my HTML/script portion: <a id="franBTN"></a> <script type="text/javascript ...

Ensure to update the canvas prior to the function finishing

Is there a way to update the canvas element while inside a JavaScript function without waiting for the function to return? It can be frustrating when you want to keep the function running but also need to update the canvas element in real time. ...

Prevent repeating the same table header multiple times when generated dynamically with jQuery

I have an array called groups which contains name and regid. I want to display the name key as the column header of a table. To achieve this, I implemented the following code: var Name = v.name; var regId = v.regid; var rowStr = '<th d ...

Output JSON data from PHP for use in Javascript

Is there a way to effectively convert JSON data from PHP/Laravel into JSON for JavaScript? I have the JSON string from PHP, but it is only rendering as a string. How can I convert it to a JSON object in JavaScript? Take a look at my code below. $('#e ...

Access the value of a variable from a window resizing event and utilize it in a different

I have a carousel that I'm working with and am trying to figure out how to announce the number of currently visible slides when the "next" button is clicked. While I can see that on resize, the correct number of slides is being logged, I am strugglin ...

Getting Started with Material UI's Default Components

After working with bootstrap, I decided to explore the material ui framework as well. However, when trying to use the default MUI component without customization, such as the card component, I encountered some difficulties. Here is an example of one of th ...

The challenge of mapping React Select

I have implemented react-select in my project and I am using it within a map function like this: renderItems() { this.props.items.map(item => ( <Select id="options" value={this.state.optionSelected} onChange={this.onChangeOpt ...

What could be causing the error "styled is not defined as a function" while creating my component library using Rollup?

Currently, I am facing an issue with my component library which is built using React, styled-components, framer-motion, Rollup, and Storybook. The library is being consumed by a NextJS website, but when trying to use it, I keep encountering the following e ...

The Vue.JS application encountered an error while making an API request, resulting in an uncaught TypeError: Cannot read properties of undefined related to the 'quote'

<template> <article class="message is-warning"> <div class="message-header"> <span>Code Examples</span> </div> <div class="message-body"> ...

Retrieve JSON information from a document through JavaScript

Is it possible to fetch JSON data using JavaScript without relying on jQuery? I am only interested in retrieving data using pure JavaScript. Here is an example of my JSON file: {"JsonProjectIDResult":[{"_capacity":15,"_description":"Meeting Room","_dev_d ...

Strip excess white space from a complex string using Javascript

I have the following sets of strings: 14/04/22 10:45:20 12.08N 87.65W 15.0 2.9ML Frente a Corinto 14/04/21 11:05:34 12.10N 87.70W 140.0 3.5MC Cerca de Masachapa 14/04/22 09:00:09 12.35N 86.44W 12.4 1.3ML Cerca del volcan Momotombo 14/04/21 23:33:37 1 ...

Tips for utilizing JavaScript to upload a file in Webform and make it accessible in the global PHP variable $_FILES

I'm feeling a little overwhelmed and frustrated. I've come across a bunch of solutions, but none of them seem to work fully or correctly!? My task is to create an HTML form that allows users to upload one or more files to the web server using AJ ...

Update the headers of the axios.create instance that is exported by Axios

I have a single api.js file that exports an instance of axios.create() by default: import axios from 'axios' import Cookies from 'js-cookie' const api = axios.create({ baseURL: process.env.VUE_APP_API_URL, timeout: 10000, headers ...

The lightbox is triggered by clicking on a different div to display its content

Great news - my lightbox is up and running! Each image on my website corresponds to a different organization, and clicking on the image opens a specific lightbox. My question is: how can I have a lightbox configured so that only the trigger image is displ ...

Angular is sending a parameter with a null value, which is not supposed to happen

My filtering system used to work well with a code that displayed items of specific status. However, I had to modify it to match a select input requirement. <ul id="dropdown-basic" *dropdownMenu class="dropdown-menu" role="menu" aria-labelledby="button- ...