Wel*_*rez 2 javascript asynchronous promise async-await
在异步函数中,我有一个循环,在这个循环中,我需要使用 await 来解析来自另一个异步函数的承诺。
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();
}
Run Code Online (Sandbox Code Playgroud)
它工作正常,但 eslint 说不允许在循环内等待并使用 Promise.all() 来解决所有承诺。
问题是我的承诺在一个对象属性中:
我怎样才能弄清楚将 Promise.all() 与对象的属性一起使用?
将 a 链接.then到lengthOfState调用上,使整个 Promise 解析为您需要的对象,在 内Promise.all:
const citiesInState = await Promise.all(
states.map(
state => lengthOfState(state.Sigla).then(cities => ({ state: state.Sigla, cities }))
)
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
125 次 |
| 最近记录: |