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

How big is the array size in the WebAudio API data?

Exploring the visualization of waveform and FFT generated by the audio stream from the microphone through the WebAudio API. Curiosity strikes - what is the size of each data array available at a given moment? Delving into the getByteTimeDomainData, it men ...

How can I automatically check all checkboxes in a row when a material table is loaded and uncheck them when clicked?

I have been working on a project using React Material Table and I am trying to figure out how to make the "select all" checkbox default checked when the page is loaded. Additionally, I want the ability to deselect any checkbox if needed. I attempted to use ...

What is the process for creating a local repository for Node.js npm?

When it comes to the building process in node js, there are a few goals that need to be called: Begin by calling npm install, which creates a folder called node_modules and places all dependencies from package.json into it. [for UI development] Execute a ...

Guide on deleting an element from an object array based on the content of a specific field (resulting in undefined mapping)

I am working on integrating a task list feature using React. I have created a state to store the id and content of each task: this.state = {tasks: [{id: 123, content: 'Walk with dog'}, {id: 2, content: 'Do groceries'}]} Adding elements ...

Data update using AJAX and codeigniter was unsuccessful

How can I update my data using Codeigniter and AJAX for submitting the response? Below is the View section of my code: <form id="form_update" action="<?php echo base_url() ?>admin/update_derap_info" method="POST" role="form"> <textare ...

React splits the page and interrupts the scroll event listener

For some reason, my webpage has been split by the React.js library. When attempting to scroll down while hovering over the top navigation menu, scrolling becomes impossible. However, scrolling works fine when done on any other part of the screen. I' ...

Verifying a checkbox selection within an Autocomplete feature using MUI

[ { label: 'First', checked: false }, { label: 'Second', checked: true } ] Here is a brief example of how the data may be structured. I am utilizing Material UI's Autocomplete feature to enable searching based on labels. Thes ...

obtaining information from newly added form elements in an Angular application

I'm currently working on an app with the MEAN stack. I've managed to dynamically add form elements, but I'm running into an issue where all dynamically added elements are taking the same data when I use ng-model="something.something". What I ...

objects bound to knockout binding effects

I have been struggling to understand why the binding is not working as expected for the ‘(not working binding on click)’ in the HTML section. I have a basic list of Players, and when I click on one of them, the bound name should change at the bottom of ...

Unlock the potential of Stripe's confirmCardSetup method when working with multiple elements in Laravel Cashier integrated with a Vue application. Master

Is it possible to send inputs separately from Stripe using the confirmCardSetup method, even though the documentation only mentions one cardElement element? https://stripe.com/docs/js/setup_intents/confirm_card_setup -> check the official documentation ...

When you click on the text, the calendar will pop up for you to

When the text "SetExpiryDate" is clicked, a date picker opens. After selecting a date, the text changes to "Expires ${date}" where the selected date is inserted. If no date is selected, the text remains as it is. I'm curious how I can implement this ...

"JQuery's selector is failing to locate elements once they have been loaded through an

I am facing an issue where jQuery selectors are not working on elements loaded from the server via Ajax requests, but they work fine in normal mode. $('#myid').change(function(){ alert('OK!'); }); <select id="myid"> <optio ...

Generate an array containing the dates of the past 30 days using Moment.js

Currently, I am utilizing momentjs in my project and aiming to generate an array that comprises of the last 30 days. My approach involves creating a counter and subsequently iterating backwards, generating a new moment instance for each day. However, I a ...

Intercepting the K-pager navigation with a pop-up modal for user confirmation before switching to a different page

Scenario Currently, I have developed a WebApp using kendo, bootstrap, and backbone. One of the key features is a grid that showcases data pulled from a database. This grid has a data source binding with serverPaging enabled. Data Source Configuration al ...

Tips on adding several elements to an array depending on the selected value from various checkboxes?

I am working on a project where I need to populate an array based on selected checkboxes. Let's assume we have 3 arrays containing strings: const fruits = ["Apple", "Banana", "Orange", "Grapes"]; const vegetable ...

Utilizing long polling technique with jQuery/AJAX on the server end

Currently, I am facing an issue with long polling on a single page that contains multiple pages. The problem arises when a new request is made while a previous request is still processing. Even though I attempt to abort the previous request, it completes b ...

Postponing the execution of a controller until all JSON files have been fully loaded

I am currently trying to grasp the concepts of AngularJS, so my question might not be perfect. Is it feasible to delay the execution of a controller until the json files are fully loaded in a separate function? Below is the controller code: app ...

update and rejuvenate session information using Node.js and express-session

Currently, I am working with Node.js in conjunction with express-session. Within my codebase, there is session data containing user information. req.session.user Upon updating the user's information, I update the session with the new data and then r ...

Steps for enabling a feature flag via API in specific environments

Within my project, I am working with three separate environments and I am looking to activate a feature flag only for a specific environment. Is it feasible to toggle an unleash feature flag using the API for just the development environment? The code snip ...

Fill a JavaScript array with values inserted in the middle position

I'm having trouble populating an array: var arr2 = ["x", "y", "z"]; I want to insert a random number/value between each original value using a for loop, like this: for (let i = 1; i < arr2.length; i+2) { arr2.splice(i, 0, Math.random()); } B ...