Reputation: 709
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
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
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
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