【问题标题】:TypeScript PromiseTypeScript 承诺
【发布时间】:2018-06-30 02:25:14
【问题描述】:

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

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

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

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

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

提前致谢。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    由于“赢家”不仅仅是第一个要解决的 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);
    

    【讨论】:

    • 我必须使用 promise.Race 功能来查看哪个 api 首先获得结果,同时我必须使用 web api 获得记录结果。
    • 上面仍然会按照 api 返回的顺序解决,模拟 Promise.race 的行为。
    • 在我的例子中 (this.custs) 是我传递的 web api 的列表,我没有在你的代码中看到 web api 的变量。
    • 我不知道 loadCustomer 在您的代码中代表什么。你能解释一下吗,我是否必须声明我是一个变量。
    猜你喜欢
    • 1970-01-01
    • 2017-12-21
    • 2017-12-22
    • 2016-08-05
    • 1970-01-01
    • 2020-03-27
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多