Inside an async function i have a loop and inside this loop i need to use await to resolve a promise from another async function.
JavaScript
x
19
19
1
async function smallestCities(states) {
2
const citiesInState = [];
3
for (const state of states) {
4
const length = await lengthOfState(state.Sigla);
5
const stateObject = {
6
state: state.Sigla,
7
cities: length,
8
};
9
citiesInState.push(stateObject);
10
}
11
12
citiesInState.sort((a, b) => {
13
if (a.cities > b.cities) return 1;
14
if (a.cities < b.cities) return -1;
15
return 0;
16
});
17
return citiesInState.filter((_, index) => index < 5).reverse();
18
}
19
It’s work fine, but eslint says to disallow await inside of loops and use Promise.all() to resolve all promises.
The problem is that my promises are in an object property:
How can i figure out to use Promise.all() with properties of an object?
Advertisement
Answer
Chain a .then
onto the lengthOfState
call to make the whole Promise resolve to the object you need, inside the Promise.all
:
JavaScript
1
6
1
const citiesInState = await Promise.all(
2
states.map(
3
state => lengthOfState(state.Sigla).then(cities => ({ state: state.Sigla, cities }))
4
)
5
);
6