Home > front end >  Access an array from promise value and make it available to be used globally
Access an array from promise value and make it available to be used globally

Time:08-02

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

CodePudding user response:

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.

  • Related