简体   繁体   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 should be stored in variable population . /api/population应该存储在变量population中。

Country, State and County should be stored in places . Country, State and County应存放在places

I would like to store the data in its corresponding variable, what is the best way to do this using Promise.all().我想将数据存储在其相应的变量中,使用 Promise.all() 执行此操作的最佳方法是什么。 How can I do this with foreach?我怎么能用foreach做到这一点?

Promise.all resolves with an array of its results wherein each result corresponds positionally to the input promise which resolved with it. Promise.all使用其结果数组解析,其中每个结果在位置上对应于使用它解析的输入 promise。

The most convenient way to assign the results to distinct identifiers is to use JavaScript's array destructuring syntax.将结果分配给不同标识符的最方便的方法是使用 JavaScript 的数组解构语法。

With async / await使用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)));

With .then.then

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

To assign to identifiers that have already been declared, you can write要分配给已声明的标识符,您可以编写

[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