Home > other >  value being returned from a promise in pending state
value being returned from a promise in pending state

Time:11-19

I'm using axios to return API data in a React app. Based on this guidance, I created this function:

function axiosGet(itemid) {
    const promise = axios(withAuth({
        url: `${apiUrl}/items/?itemid=${itemid}`
    }))
    const dataPromise = promise.then((response) => response.data)
    return dataPromise
}

and this code to invoke it:

const getData = (theitemid) => {
    const itemdata = axiosGet(theitemid)
        .then(data => {
            console.log(data.length);  // correctly prints the value I want
            return data.length
        })
        .catch(err => console.log(err))

    console.log(itemdata) // at this point, itemdata is: Promise {<pending>}
    return itemdata
}

I want getData to return the resolved value returned from axiosGet.

But instead of being resolved, it's in pending status.

Is there some way I can hold off on returning itemdata until it is actually resolved?

CodePudding user response:

you have two many options, you can return promise or await the result

const getData = async (theitemid) => {
    const itemdata = await axiosGet(theitemid)
        .then(data => {
            console.log(data.length);  // correctly prints the value I want
            return data.length
        })
        .catch(err => console.log(err))

    console.log(itemdata) // at this point, itemdata is: Promise {<pending>}
    return itemdata
}

CodePudding user response:

In your case, getData is basically the same thing as axiosGet, the fact that you went ahead and created getData to me is an indicator that your difficulty is with using functions that return promises.

Such functions are also called, asynchronous functions.

Do not despair, this is not an easy thing to grasp, especially for self-taught web developers in 2022.

I hope this code might help you wrap your head around what you want to do:

// setup 1: rename axiosGet to getData            
  • Related