typescript - TypeScript 承诺
问题描述
我有下面的代码行,我得到了结果。
Promise.race(this.custs).then(Winner=> {
this.Winner= Winner;
});
如果比赛中的第一个 Web api 的记录为零,我想继续下一个 webApI。
换句话说,我想从有记录的获胜者那里得到结果。
this.custs 数组变量有 n 个 webapi。
提前致谢。
解决方案
由于“赢家”不仅仅是第一个要解决的 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);
推荐阅读
- bash - 将 STDOUT 重定向到新窗口,将 STDERR 重定向到相同的新窗口以及日志文件
- java - javafx重新计算父/节点边界时如何修复IndexOutOfBounds异常
- python - 对数据框进行操作以将行转换为单独的列
- django - 将列表值从 django 模板发送到 django 视图
- unity3d - 如何解决“统一 AR 项目中的重力问题”
- bash - 填充csv的列
- javascript - 尝试使用签名方法将文件上传到 S3 时如何修复“SignatureDoesNotMatch”错误
- java - 如何在像 FB Messenger 这样的 android 中“自动更改”状态栏文本颜色?
- c# - 如何修复 Vector2.Distance() 方法?
- javascript - 如何反转 d3 色带 d3-scale-chromatic d3.interpolateViridis