我正在编写一些打字稿来为网络应用程序构建带有远程数据的“系统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)
}
})
也许是这样的:
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)
}