在RxJS Observable flatMap中运行等待

时间:2018-12-31 14:04:52

标签: asynchronous async-await rxjs observable flatmap

我试图在传递给flatMap的异步箭头函数中返回一个observable,但是未调用返回的observable。

protected buildUseCaseObservable(params: LoginUserParams): Observable<Session> {
        return this.userRepository.getUserByName(params.getUsername())
            .pipe(flatMap(async user => {
                if (!user) {
                    throw new Error(Errors.USER_DOESNT_EXIST);
                }

                const match = await this.cypher.compare(params.getPassword(), user.password);
                if (!match) {
                    throw new Error(Errors.WRONG_PASSWORD);
                }

                return Observable.create((subscriber: Subscriber<Session>) => {
                    subscriber.next(new Session("token test", "refreshToken test"));
                    subscriber.complete();
                });
            }));
    }

有人知道它为什么会发生,我该如何解决?预先感谢。

1 个答案:

答案 0 :(得分:0)

解决了,我只是将诺言变成了可观察的东西,并做了flatMap。

protected buildUseCaseObservable(params: LoginUserParams): Observable<Session> {
        return this.userRepository.getUserByName(params.getUsername())
            .pipe(flatMap(storedUser => {
                if (!storedUser) {
                    throw new Error(Errors.USER_DOESNT_EXIST);
                }

                return from(this.cypher.compare(params.getPassword(), storedUser.password));
            })).pipe(flatMap(match => {
                if (!match) {
                    throw new Error(Errors.WRONG_PASSWORD);
                }

                return Observable.create((subscriber: Subscriber<Session>) => {
                    subscriber.next(new Session("token test", "refreshToken test"));
                    subscriber.complete();
                });
            }));
    }