0

I am receiving an array from a promise function:

function func() {
    return new Promise((resolve, reject) => {
        //...
        return someData;
    })
}

then I can see the promise value using async/await:

async function getArrayContent() {
    const a = await func();
    console.log(a);
}

this does display the correct content however, I am looking to access the array and its contents in so it can be used outside the async getArrayContent() function. please note that I can't change func() as the promise is necessary to return data I am retrieving. Also, return a does not work because whenever I am logging the getArrayContent() which returns a it just shows another pending promise. However, in this promise it does show that the state is fulfilled and it does have the necessary value but I still cannot access that value outside the functions. I tried adding a variable outside getArrayContent() but variable remains undefined. I am using this in Reactjs and some of the solutions I tried both did not work and/or caused an infinite loop. Other posts on stackoverflow did not help either because they only shows how to log value inside a promise with .then() which I cannot use.

I need to be able to display the area in React with the map function

09fgjbHH90_
  • 53
  • 1
  • 6
  • 1
    Once in async land, always in async land. Though as regards React you can `setState` with `a` inside the async function and it will update state as expected and be available the next render cycle. – pilchard Aug 01 '22 at 20:21
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – pilchard Aug 01 '22 at 20:22
  • 1
    also see: [How to call an async function inside a UseEffect() in React?](https://stackoverflow.com/questions/56838392/how-to-call-an-async-function-inside-a-useeffect-in-react) – pilchard Aug 01 '22 at 20:25

1 Answers1

1

There is no way to do precisely what you are asking here.

As @pilchard succinctly said:

Once in async land, always in async land.

However, one thing you could do is, await the function and pass it as a prop to a child component (and only show the child component when the data is ready), Now you can use the value synchronously in the child component.

Mahdi Ghajary
  • 2,717
  • 15
  • 20