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;

Mikhail Kostiuchenko
  • 9,121
  • 4
  • 15
  • 28

1 Answers1

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);
        }));
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • 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` – mahmoudafer May 26 '20 at 09:29