首页 > 解决方案 > 动作分派时中止承诺链(rxjs)

问题描述

这是我想要实现的目标:

this.jobManager
    .queue(
        // start a job
    )
    .then(
        // do more stuff, but abort if `ABORT` action dispatched before it finishes
    )
    .finally(
        // still do some cleanup even if `ABORT` dispatched
    );

这是我“尝试过的”:

this.actions$.pipe(
    ofActionDispatched(ABORT)
    .subscribe(() => {
        // somehow interrupt the promise chain in the above code block...
    })
);

希望我已经充分传达了所需的逻辑。我认为这两者需要组合成一个单一的承诺链,但我不确定如何做到这一点。

标签: javascriptangularrxjs5

解决方案


我不是 100% 确定你的 ofActionDispatched 函数是如何工作的,但是如果它需要中止,你能不能让它抛出一个错误,然后使用 catchError 返回一个空值,然后在订阅中检查它,如下所示:

this.actions$.pipe(
            map(obj => {
                // do stuff
            }),
            catchError(err => {
                return of(null);
            }))
        .subscribe((res) => {
                if (!res) {
                    // do stuff if error was caught in pipe
                }
            })

推荐阅读