简体   繁体   English

Promise.all() 等待 object 属性的返回

[英]Promise.all() to await the return of an object property

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.在异步 function 中我有一个循环,在这个循环中我需要使用 await 从另一个异步 function 解析 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();
}

It's work fine, but eslint says to disallow await inside of loops and use Promise.all() to resolve all promises.它工作正常,但 eslint 说禁止在循环内等待并使用 Promise.all() 来解决所有承诺。

The problem is that my promises are in an object property:问题是我的承诺在 object 属性中:

函数的返回

How can i figure out to use Promise.all() with properties of an object?我怎样才能弄清楚将 Promise.all() 与 object 的属性一起使用?

Chain a .then onto the lengthOfState call to make the whole Promise resolve to the object you need, inside the Promise.all :.then链接到lengthOfState调用上,使整个 Promise 解析为您需要的 object,在Promise.all

const citiesInState = await Promise.all(
  states.map(
    state => lengthOfState(state.Sigla).then(cities => ({ state: state.Sigla, cities }))
  )
);
const NEW_LAND = 'newLand'
const ACTUAL_FINLAND = 'actualFinland'
const PIRKKAS_LAND = 'pirkkasLand'

const STATE_CITY_MAP = {
  [NEW_LAND]: ['HELSINKI', 'VANTAA', 'KORSO'],
  [ACTUAL_FINLAND]: ['TURKU'],
  [PIRKKAS_LAND]: ['WHITE RAPIDS', 'NOKIA'],
}

const mockGetCities = (stateName) => new Promise((res) => {
  setTimeout(() => { res([stateName, STATE_CITY_MAP[stateName]]) }, 0)
})

const compareStatesByCityQty = (a, b) => {
  if (a[1].length > b[1].length) return 1
  if (a[1].length < b[1].length) return -1
  return 0
}

const getSmallestStates = async (stateNames, cityQty) => {
  const cities = await Promise.all(stateNames.map(mockGetCities))
  return cities
    .sort(compareStatesByCityQty)
    .reverse()
    .slice(0, cityQty)
}

;(async () => {
  const stateNames = [NEW_LAND, ACTUAL_FINLAND, PIRKKAS_LAND]
  const smallestStates = await getSmallestStates(stateNames, 2)
  console.log(smallestStates)
})()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM