0

I have an async function:

 const _getSelectedComponentVariantByComponentName = async (name) => {
            const response = await api.get(`/internal/api/Component/GetComponentVariantByComponentName/${name}`);

            componentRow.component = response.data;
            return componentRow;
        };

And I'm trying to use this function inside .map() method:

let componentRows = [...getState().formulaBuilder.componentRows];
componentRows = componentRows.map(async row => {
                row  = await _getSelectedComponentVariantByComponentName(row.name);
                return row;
            });

But in this case I got a Promise with status "pending". How to wait for completion of async api call and return a value;

3
  • 2
    Use await Promise.all(array) Commented May 26, 2020 at 9:23
  • Do you really want to await each item consistently? Looks like a perfect use case for Promise.all Commented May 26, 2020 at 9:23
  • 1
    Does this answer your question? Best way to call an async function within map? Commented May 26, 2020 at 9:26

1 Answer 1

2

You can make use of Promise.all with map and use await with it.

map will return an array of Promises, Promise.all will wait for all promises to resolve and then resolve with the values as an array for each promise.

Also make sure you execute the below code in an async function:

 let componentRows = [...getState().formulaBuilder.componentRows];
  componentRows = await Promise.all(componentRows.map(row => {
            return _getSelectedComponentVariantByComponentName(row.name);
        }));
Sign up to request clarification or add additional context in comments.

1 Comment

good answer but i think it needs a little more info: async functions always return a promise, and the map function returns an array of whatever is returned from the callback inside, which is a promise, so in js we can wait for all promises to resolve in an array by using Promise.all

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.