gpt4 book ai didi

Javascript/Typescript 如何并行运行异步函数?

转载 作者:行者123 更新时间:2023-12-01 01:20:29 24 4
gpt4 key购买 nike

我有一段运行 4 async 的代码功能:

this.groupsLevels = await this.groupsLevelsService.getData();
this.indicators = await this.configurationService.getIndicators();
this.sources = await this.configurationService.getSources();
this.storeGroups = await this.storeGroupsService.getStoreGroups();

console.log(this.groupsLevels) // All of them is populated
console.log(this.indicators) // All of them is populated
console.log(this.sources) // All of them is populated
console.log(this.storeGroups) // All of them is populated

如何并行运行全部 4 个?全部完成后得到最终结果。?

我试过了

Promise.all([
async () => {this.groupsLevels = await this.groupsLevelsService.getData(); },
async () => {this.indicators = await this.configurationService.getIndicators(); },
async () => {this.sources = await this.configurationService.getSources(); },
async () => {this.storeGroups = await this.storeGroupsService.getStoreGroups(); },
]);

console.log(this.groupsLevels)
console.log(this.indicators)
console.log(this.sources)
console.log(this.storeGroups)

但是没有人加载成功。

我做错了什么?

最佳答案

您正在寻找

[this.groupsLevels, this.indicators, this.sources, this.storeGroups] = await Promise.all([
this.groupsLevelsService.getData(),
this.configurationService.getIndicators(),
this.configurationService.getSources(),
this.storeGroupsService.getStoreGroups(),
]);

console.log(this.groupsLevels);
console.log(this.indicators);
console.log(this.sources);
console.log(this.storeGroups);

关于Javascript/Typescript 如何并行运行异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54280078/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com