繁体   English   中英

使用 Promise.all 存储不同类型数据的最佳方法是什么?

[英]What is the best way to store different types of data with a 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做到这一点?

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

将结果分配给不同标识符的最方便的方法是使用 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)));

暂无
暂无

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

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