RXJS toPromise行为不同于可观察到的行为 [英] Rxjs toPromise behavior different than observable

查看:132
本文介绍了RXJS toPromise行为不同于可观察到的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的示例,其中两个方法创建并返回一个Promise.第二个方法buildRedCar()调用第一个方法buildCar(),修改promise返回的值,并从其自身返回另一个promise.然后代码调用buildRedCar(),只是console.log输出结果.转换为Promise时,此方法不起作用,但使用直接可观察变量时,它确实起作用.

I have a simple example where two methods create and return a promise. The second method buildRedCar() calls the first method buildCar(), modifies the value returned by the promise and returns another promise from itself. The code then calls buildRedCar(), and just console.logs the result out. This does not work when converting to promises, but it does work when using straight observables.

有效:

import * as Rx from 'rx';

function buildCar(): Rx.IPromise<string> {
    let car = 'Car';
    return Rx.Observable.just<string>(car).toPromise();
}

function buildRedCar(): Rx.IPromise<string> {
    let observable = Rx.Observable.create<string>((observer) => {
        buildCar().then((car) => {
            observer.onNext('Red ' + car);
        });
    })

    return observable.toPromise();
}

buildRedCar().then((car) => {
    console.log(car);
});

可以工作:

import * as Rx from 'rx';

function buildCar(): Rx.Observable<string> {
    let car = 'Car';
    return Rx.Observable.just<string>(car);
}

function buildRedCar(): Rx.Observable<string> {
    let observable = Rx.Observable.create<string>((observer) => {
        buildCar().subscribe((car) => {
            observer.onNext('Red ' + car);
        });
    })

    return observable;
}

buildRedCar().subscribe((car) => {
    console.log(car);
});

有什么主意,为什么唯一的区别就是在返回之前将可观察到的东西转换成一个承诺,但这种不同的行为呢?

Any idea why the different behavior when the only difference is converting the observable to a promise before returning?

推荐答案

当RxJs将Observable转换为Promise时,它将创建Promise,该Promise将从Observable中产生 last 值.因此,直到基础的可观察对象完成后,诺言才得以解决.

When RxJs converts an Observable to a Promise, it creates a Promise that will yield the last value from the observable. Thus the promise will not resolve until the underlying observable completes.

在第一个示例中(以及第二个示例中),您从未完成可观察到的红色汽车.因此,诺言永远无法解决.因此,包装诺言的可观察对象永远不会产生价值...

In your first example (and in your second as well), you never complete the red car observable. Therefore the promise never resolves. Therefore the observable that wraps the promise never produces a value...

您的第二个示例之所以有用,是因为订阅会急切地打印出您的红色汽车在到达时可观察到的第一个值,然后等待"从未到达的其他结果.

Your 2nd example works because the subscription eagerly prints the first value produced by your red car observable as it arrives, and then "waits" for further results that never arrive.

onComplete添加呼叫应该可以使您的第一个版本正常工作

Adding a call to onComplete should make your first version work:

observer.onNext('Red ' + car);
observer.onComplete();

这篇关于RXJS toPromise行为不同于可观察到的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆