axios.get consistently delivers a Promise of type <Pending>

I have been searching for a solution to my issue, but so far none of the suggestions have worked for me. Below is the code that I am struggling with:

const Element = () => {
        async function getEndData() {
            const data = (await getEnd());
            return data;
        }
}

const getEnd = async () => {
    return await axios.get('http://localhost:8080/end').then(res => res.data);
}

Every time I call getEndData(), it always returns a Promise "pending" with the value I need inside a [[PromiseResult]]. I even tried calling getEnd() directly without using then() and only returning the data, but still no luck. When I print res.data in the console log, it shows the correct value that I need.

Answer №1

This is a possible solution:

function Component() {
  async function fetchEndData() {
    const data = await fetchData();
    return data;
  }
}

async function fetchData() {
  const response = await axios.get('http://localhost:8080/data');
  return response;
}

Answer №2

Perhaps there is a better approach to tackle this issue. Consider the following solution:

const Element = () => {
        return async function retrieveEndData() {
            const data = await fetchEnd();
            return data;
        }
}

const fetchEnd = () => {
    return new Promise((resolve, reject) => {
     axios.get('http://localhost:8080/end')
     .then(res => {
      resolve(res.data)
     })
     .catch(err => {
         reject(err);
      })
    }) 
}

Additionally, it seems the element function serves no purpose if it does not have a return value.

Answer №3

When using getEndData(), make sure to handle the returned promise properly by either using await or then.

// const Element = () => {
    async function getEndData() {
        const data = (await getEnd());
        return data;
    }
// }

const getEnd = async () => {
    return await axios.get('http://localhost:8080/end').then(res => res);
}



async function callEndData(){
    let x = await getEndData()
    console.log(x)
}
callEndData()

If you encounter a 'promise pending' message, it means you are not correctly handling the promise being returned.

Consider if you really need the Element() function and how you can efficiently retrieve data from the response.

You can modify your code structure to combine Element function and data retrieval like this:


const Element = async() => {
    async function getEndData() {
       return await getEnd();
    }

    let fromEndData  = await getEndData()
    return fromEndData 
}

const getEnd = async () => {
    return axios.get('http://localhost:8080/end').then(res => {
       return res.data
    });
}



async function callEndData(){
    let x = await Element()
    console.log(x)
}
callEndData() 

The value being passed is displayed in the console.log(x) statement.

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

Upgrade the WordPress light editor to the advanced version

After developing a script to upgrade the WordPress editor on a specific page from light mode to Advanced once a user clicks the Unlock button and confirms their desire to make the switch, an issue arose. Despite deducting 5 coins from the user's balan ...

What is the best way to use JavaScript to click on a block and retrieve its attribute value?

Struggling to capture the data-id attribute value of each item on click, despite researching online. Seeking guidance as I navigate the learning process and encounter programming frustrations. document.addEventListener("click", handle); const demo = e. ...

Checkbox inputs with activated labels causing double events to fire

Creating round checkboxes with tick marks dynamically and appending them to id="demo" on the click of two buttons that invoke the get(data) method is my current goal. The issue arises when both buttons are clicked simultaneously, as the checkboxes do not ...

Ensured static element-UI table dimensions even with modifications to columns

Creating an Element-UI table and using v-if to control column show/hide has been working perfectly, except for one small issue. The table seems to automatically change size when columns are shown/hidden, even though I have already set fixed width and heig ...

Add some texture to one side of the quadrilateral

I have a project in threejs where I need to display an image of a cat within a rectangle. The challenge is to render the right half of the rectangle in red, while displaying the full stretched image of the cat on the left half. Here's my current scen ...

It is impossible to add a new element between two existing elements that share the same parent

I'm attempting to place an <hr> tag between the first and second .field-container. Because they have the same parent, I thought using element1.parentNode.insertBefore(element2, ...) would be the solution. However, it is not working as expected a ...

Issue with Datepicker validation in Angular 5 and Angular Material

I have implemented the most recent version of Angular and Angular Material. I am facing an issue with a datepicker where the validation requirements are not being met as expected. The documentation states that the required attribute should work by default, ...

Google Tag Manager experiencing issues with retrieving dataLayer variable, showing as undefined

I'm attempting to establish a dataLayer variable in order to push the product name into the event label. Here is the dataLayer push that occurs when a user adds a product to their cart: { event: "addToCart", gtm: { uniqueEventId: 10 ...

Encountering a node.js issue

Hi there, I keep encountering this error message. Can someone explain what it means? I'm not very skilled in coding, so I would appreciate any assistance :) Best regards logon fail: 65, sessionID: 6343803 events.js:85 throw er; // Unhandled & ...

Deduce the generic types of conditional return based on object property

My goal is to determine the generic type of Model for each property. Currently, everything is displaying as unknown[] instead of the desired types outlined in the comments below. playground class Model<T> { x?: T } type ArgumentType<T> = T ...

Ensure that text is aligned alongside an image only when both elements are enclosed within <p> tags

When using an API to pull markdown content from Contentful and converting it to HTML with ReactMarkdown, a common issue arises. The resulting HTML structure often places the text content in separate paragraphs such as: <p>Some text content</p> ...

Adjust the minimum height and width when resizing the window

Apologies in advance if this has already been addressed, but I have tried solutions from other sources without success. My Objective: I aim to set the minimum height and width of a div based on the current dimensions of the document. This should trigger ...

What is the proper way to specify the type for the iterable response of Promise.all()?

It's common knowledge that Promise.all will return settled promises in the same order of the requested iterable. I'm currently grappling with how to correctly define types for individual settled resolves. I am utilizing Axios for handling asynch ...

Troubleshoot: Dropdown menu in Materialize not functioning (menu fails to drop down

I am currently incorporating Materialize to create a dropdown button in my navigation bar. However, I am facing an issue where nothing happens when the button is clicked. Here is a snippet of my code: <head> <meta charset="UTF-8"> <!-- ...

What are some techniques for applying CSS styling directly to a custom element?

Check out this amazing resource from HTML5 Rocks about the process of creating custom elements and styling them. To create a custom element, you can use the following code: var XFoo = document.registerElement('x-foo', { prototype: Object.crea ...

Development of a chart application involving frontend and backend components, utilizing chartjs for data visualization, mongodb for storage

As a beginner in generating charts using the ajax mechanism and chartjs, I've encountered an issue where the graphs are being plotted incorrectly. Any guidance on how to improve would be greatly appreciated. Thank you! Here is my JavaScript code for ...

Issue with Angular 7 Universal: components inside are failing to display

I have successfully implemented Angular 7 Universal with dynamic server-side rendering. However, I am facing an issue where dynamic components within the main component being rendered on the server are not rendered themselves. Here is an example of the re ...

Experiencing difficulties with a click event function for displaying or hiding content

Struggling with implementing an onClick function for my two dynamically created components. Currently, when I click on any index in the first component, all content is displayed. What I want is to show only the corresponding index in the second component ...

Exploring the principles of object-oriented design within the context of Node

I am facing challenges with the asynchronous flow of Node.js. Let's assume we have the following class: function myClass() { var property = 'something'; var hasConnected = false; this.connect = function(params) { // Logic to conn ...

Refreshing Child's Activities

In my scenario, I am displaying data in a child action and utilizing buttons to modify the displayed information. Here is an example of how I am achieving this: Index.cshtml <head> <script type="text/javascript"> $("#RefreshView").on ...