在异步函数内部我有一个循环,在这个循环内部我需要使用 await 来解决来自另一个异步函数的 promise 。
async function smallestCities(states) {
const citiesInState = [];
for (const state of states) {
const length = await lengthOfState(state.Sigla);
const stateObject = {
state: state.Sigla,
cities: length,
};
citiesInState.push(stateObject);
}
citiesInState.sort((a, b) => {
if (a.cities > b.cities) return 1;
if (a.cities < b.cities) return -1;
return 0;
});
return citiesInState.filter((_, index) => index < 5).reverse();
}
它工作正常,但 eslint 说禁止在循环内等待并使用 Promise.all() 来解决所有 promise 。
问题是我的 promise 是在一个对象属性中:
我怎样才能确定将 Promise.all() 与对象的属性一起使用?
最佳答案
将 .then
链接到 lengthOfState
调用上,以使整个 Promise 解析为您需要的对象,在 Promise.all
内:
const citiesInState = await Promise.all(
states.map(
state => lengthOfState(state.Sigla).then(cities => ({ state: state.Sigla, cities }))
)
);
关于javascript - Promise.all() 等待对象属性的返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65175124/