首页 > 解决方案 > TypeScript 承诺

问题描述

我有下面的代码行,我得到了结果。

Promise.race(this.custs).then(Winner=> {
  this.Winner= Winner;      
});

如果比赛中的第一个 Web api 的记录为零,我想继续下一个 webApI。

换句话说,我想从有记录的获胜者那里得到结果。

this.custs 数组变量有 n 个 webapi。

提前致谢。

标签: typescript

解决方案


由于“赢家”不仅仅是第一个要解决的 Promise,因此您需要超越使用Promise.race. 我不确定您如何触发异步请求的确切结构,但希望将以下内容映射到您所拥有的内容上应该很容易:

const winner = null;

const customerIds: string[] = ['1', '2', '3', /* ... */];

const customers: Promise<Customer>[] = customerIds.map(
  id => loadCustomer(id).then(customer => {
    if (!winner && customer.records.length > 0) {
      winner = customer;
      // We have a winner, do whatever else you need to with it
  }
);

我们在这里所做的只是检查每个加载的客户,如果我们已经有赢家,以及加载的客户是否有任何记录。如果我们还没有赢家,而这个客户有记录,他们就是赢家。

然后在任何时候,如果您还关心知道何时加载所有客户,您可以简单地:

Promise.all(customers);

推荐阅读