gpt4 book ai didi

javascript - 如何摆脱具有早期返回的多个嵌套 switchMap

转载 作者:行者123 更新时间:2023-12-03 16:19:07 28 4
gpt4 key购买 nike

我有 3 个端点返回即将发生的、当前的、过去的事件。我应该只显示 future 最远的那个。为了优化调用而不是一次调用所有端点。我编写了一个简单的 RxJs 流,我在其中调用第一个端点,如果它不返回数据,我调用第二个,依此类推。代码如下所示:

this.eventsService.getUpcoming(id).pipe(
switchMap((upcoming) => {
if (upcoming.length) {
return of(upcoming);
}
return this.eventsService.getCurrent(id).pipe(
switchMap((current) => {
if (current.length) {
return of(current);
}
return this.eventsService.getPast(id)
})
);
}),
// some other pipe operators map etc.

开关映射中可以没有嵌套的开关映射吗?

最佳答案

我认为你可以只使用 concat()使调用顺序,然后 take(1)skipWhile()当第一个有用的响应到达时自动完成:

concat(
this.eventsService.getUpcoming(id),
this.eventsService.getCurrent(id),
this.eventsService.getPast(id)
).pipe(
skipWhile(response => response.length === 0),
defaultIfEmpty([]),
take(1),
);
take(1)将在 skipWhile 中的第一项时完成链不符合条件。

关于javascript - 如何摆脱具有早期返回的多个嵌套 switchMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67386779/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com