我有一段这样的代码:
source$.pipe(
exhaustMap(input => ajaxPost1(input)), // ajaxPost1 returns ajaxObservable
tap(console.log), // can print HTTP response
exhaustMap(({result}) => ajaxPost2(result)), // ajaxPost2 returns promise
tap(console.log), // print nothing sometimes even if promise has been resolved and I don't know why
)
.subscribe(...);
并且ajaxPost2
实际上是一个名为handlePrecheck
的函数,如下所示:
handlePrecheck(precheckResponse) {
const {response, request} = precheckResponse;
if (!response.status) {
this.displayInfo(response.msg);
return Promise.resolve(null);
}
// 早退时,签到流程是否继续由UI决定
if (response.isEarlyCheckout) {
// const a = this.confirmEarlyCheckout(precheckResponse);
// window.a = a;
// console.log(a);
// return a;
return this.confirmEarlyCheckout(precheckResponse);
}
if (response.holidayToCancel && response.holidayToCancel.id) {
const {id, duration} = response.holidayToCancel
this.confirmCancelHoliday(request.body.get('picture'), duration, id);
// 当有假期时总是终止签到过程
return Promise.resolve(null);
}
return Promise.resolve(precheckResponse);
}
[this.confirmEarlyCheckout
是一种返回诺言的方法,该诺言将根据UI事件很快得到解决(我可以通过在dev工具中检查诺言对象来确认这一点)。
handlePrecheck
仅在进入if(response.isEarlyCheckout)
分支时不会将值传递给下游,但是在进入其他分支并返回Promise时效果很好。
非常感谢任何人能提供帮助。
[exhaustMap()]运算符将源值投影到内部可观察值中,该内部可观察值合并在输出可观察值中,因此您需要返回一个可观察值而不是承诺。
您可以使用RxJS from()运算符将您的承诺简单地转换为可观察的。它的作用是将数组,promise或Iterable转换为可观察对象,从而使您可以返回exhaustMap()
序列上的可观察对象。
source$.pipe(
exhaustMap(input => from(ajaxPost1(input))),
tap(console.log),
exhaustMap(({result}) => from(ajaxPost2(result)))
tap(console.log),
)
.subscribe(...);
请记住以这种方式导入它:
import { from } from 'rxjs';
确定...我已经找到原因...在等待UI事件解决Promise时取消订阅source$
,因此Promise的已解决值不会传递到下游