Mohamed Daher
Mohamed Daher

Reputation: 709

Use the result of an async API call inside a forEach

I am calling an API that return a list of users as follows:

const users = await axios.get('/api/users/all');

res.data now is an array of my users who each have a field called manager that is an id of a manager from another Schema I have another API that returns a manager name when their id is provided

axios.get('/api/managers/managerName', id)

I want to run a forEach to insert the manager name to my result instead of his id. I am trying

const users= await axios.get('/api/users/all');
const final = users.data.forEach(function (element) {
      element.managerName= axios.get('/api/managers/managerName', element.id);
    });

But of course this doesnt work since axios.get('/api/managers/managerName', element.id) returns a promise. How can i fix this? Thank you

Upvotes: 1

Views: 1128

Answers (3)

Jeremy Thille
Jeremy Thille

Reputation: 26370

As far as I can tell, you can't use await inside forEach or map. It doesn't work (doesn't await). You have to use a for loop.

for( let element of users.data) {
    element.managerName = await axios.get('/api/managers/managerName', element.id);
}

Upvotes: 4

Greedo
Greedo

Reputation: 3549

You can resolve your second promise:

const final = users.data.forEach(async function (element) {
      element.managerName= await axios.get('/api/managers/managerName', element.id).then((manager) => manager.name);
    });

Upvotes: 1

Oleksandr K
Oleksandr K

Reputation: 357

const users= await axios.get('/api/users/all');
const final = Promise.all(
users.data.map(async (element) => {
      element.managerName = await axios.get('/api/managers/managerName', element.id);
    }));

Upvotes: 1

Related Questions