Is there any way to use Promise.all in my case ? Should i use two different loop (one to push in an array of promise and another to push each result to the right place) ?
(This is just an example and my current code contains much more data, so using Promise.all seems very interesting since the requests are independent of each other)
const myFunction = async ()=>{
let someData=[{ID:55,name:'name1',firstname:'fname1',address:'address1'},
{ID:26,name:'name2',firstname:'fname2',address:'address2'},
{ID:88,name:'name3',firstname:'fname3',address:'address3'}]
for (let i = 0; i < someData.length; i++) {
someData[i].country = await getCountryFromDatabase(someData[i].ID)
}
}
Thank you
Map the array to an array of promises, using the reference to the object you have in the mapping callback to mutate it after the API call finishes.
let someData = [{ ID: 55, name: 'name1', firstname: 'fname1', address: 'address1' },
{ ID: 26, name: 'name2', firstname: 'fname2', address: 'address2' },
{ ID: 88, name: 'name3', firstname: 'fname3', address: 'address3' }]
await Promise.all(
someData.map(obj => (
getCountryFromDatabase(obj.ID).then((country) => {
obj.country = country;
})
))
);