【问题标题】:What is the best way to store different types of data with a Promise.all?使用 Promise.all 存储不同类型数据的最佳方式是什么?
【发布时间】:2020-08-11 00:06:53
【问题描述】:
population: {[id: number]} = {}
places: {[id: string]} = {}

const promises = ['/api/population',
            '/api/data/Country',
            '/api/data/State', 
            '/api/data/County']
             .map(api => fetch(api)

/api/population 应该存储在变量population 中。

Country, State and County 应该存储在places 中。

我想将数据存储在其对应的变量中,使用 Promise.all() 执行此操作的最佳方法是什么。如何使用 foreach 做到这一点?

【问题讨论】:

  • 如何在一个变量中存储三个值?
  • 嗯,我正在考虑使用 forEach,但我想这不好,因为每个 API 都存储在不同的变量中。
  • forEach 几乎总是错误的选择 :-)
  • @Bergi 哈哈。如此真实。

标签: javascript typescript api promise


【解决方案1】:

Promise.all 使用其结果数组解析,其中每个结果在位置上对应于使用它解析的输入承诺。

将结果分配给不同标识符的最方便的方法是使用 JavaScript 的数组解构语法。

async/await

const [populations, countries, states, counties] = await Promise.all([
   '/api/population',
   '/api/data/Country',
   '/api/data/State',
   '/api/data/County'
].map(api => fetch(api)));

.then

Promise.all([
   '/api/population',
   '/api/data/Country',
   '/api/data/State',
   '/api/data/County'
].map(api => fetch(api)))
  .then(([populations, countries, states, counties]) => { });

要分配给已经声明的标识符,你可以写

[populations, countries, states, counties] = await Promise.all([
   '/api/population',
   '/api/data/Country',
   '/api/data/State',
   '/api/data/County'
].map(api => fetch(api)));

【讨论】:

  • 谢谢!所以 forEach 不是正确的做法,对吧?另外,让 Promise.all 处理所有承诺是常见的做法吗?
  • 是的,这是一种常见的做法。 for each 的问题在于它不返回值 - 替代方案实际上是 map 或 reduce
猜你喜欢
  • 2022-09-27
  • 2011-08-09
  • 1970-01-01
  • 2017-05-21
  • 1970-01-01
  • 2017-03-26
  • 2013-07-22
  • 2021-10-22
  • 1970-01-01
相关资源
最近更新 更多