javascript - 使用 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
使用其结果数组解析,其中每个结果在位置上对应于使用它解析的输入承诺。
将结果分配给不同标识符的最方便的方法是使用 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)));
推荐阅读
- docker - 仅将 Docker Swarm Manager 节点公开到 Internet。隐藏工作人员(无公共 IP)
- javascript - 在 Electron 的渲染器中导出/定义函数的正确方法
- flutter - 使 BLoC 状态持久化,以便使用 Flutter 制作离线应用程序
- angular - Angular 7,命名路由器插座在延迟加载的模块中不起作用
- java - 转换列表
> 流式传输 - java - 如何解决:“StepsCode 类型的层次结构不一致”问题
- javascript - 引导多选不是一个功能 - 不检查多选脚本
- java - 如何通过 Jenkins 定位特定的 Cucumber 功能文件(自动化测试)?
- actionscript-3 - 在 Adobe AIR windows 应用程序中调整舞台大小
- karate - 检查标头是否包含有效的 UUID