首页 > 解决方案 > 使用 Promise.all 存储不同类型数据的最佳方式是什么?

问题描述

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做到这一点?

标签: javascripttypescriptapipromise

解决方案


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)));

推荐阅读