等待多个 Promise 并存储它们的最佳方式是什么?

问题描述 投票:0回答:1

我正在编写一些打字稿来为网络应用程序构建带有远程数据的“系统chache”。

所以我想知道的是“最明智”的方法来做到这一点。我写了 3 种不同的方法,但我不确定它们是否有任何好处。

示例 1 - 嵌套订阅者:

this.client.getEmployees().subscribe({
  next: (r1) => {
    this.system.setEmployees(r1);

    this.client.getCustomers().subscribe({
      next: (r2) => {
        this.system.setCustomers(r2);

        this.client.getCustomerTypes().subscribe({
          next: (r3) => {
            this.system.setCustomerTypes(r3);
        });
    });
});

示例 2 - 等待的承诺:

const $employees = firstValueFrom<Employee[]>this.client.getEmployees());
this.system.setEmployees(await $employees);

const $customers = firstValueFrom<Customer[]>(this.client.getCustomers());
this.system.setCustomers(await $customers);

const $customerTypes = firstValueFrom<CustomerType[]>(this.client.getCustomerTypes());
this.system.setCustomerTypes(await $customerTypes);

示例 3 - Promise.allSetted 使用“setter”数组:

const promises = await Promise.allSettled([
  firstValueFrom<Employee[]>(this.client.getEmployees()),
  firstValueFrom<Customer[]>(this.client.getCustomers()),
  firstValueFrom<CustomerType[]>(this.client.getCustomerTypes())
])

const setters = [
  this.system.setEmployees,
  this.system.setCustomers,
  this.system.setCustomerTypes
]

promises.forEach((promise, index)=> {
  if(promise.status === "fulfilled") {
    setters[index](promise.value)
  }
})
typescript async-await promise rxjs
1个回答
0
投票

也许是这样的:

 var promises = [
  this.client.getEmployees(),
  this.client.getCustomers(),
  this.client.getCustomerTypes()
 ]
 Promise.all(promises).then((values) => {
  const [employees, customers, customerTypes] = values

  this.system.setEmployees(eployees)
  this.system.setCustomers(customers)
  this.system.setCustomerTypes(customerTypes)
 }
© www.soinside.com 2019 - 2024. All rights reserved.