Chaining promises with RxJS

前端 未结 3 2056
青春惊慌失措
青春惊慌失措 2020-12-15 09:15

I\'m new to RxJS and FRP in general. I had the idea of converting an existing promise chain in my ExpressJS application to be an observable for practice. I am aware that thi

相关标签:
3条回答
  • 2020-12-15 09:44

    Observable.forkJoin works great here receiving array of other Observables.

    Rx.Observable.forkJoin([this.http.get('http://jsonplaceholder.typicode.com/posts'), this.http.get('http://jsonplaceholder.typicode.com/albums')]).subscribe((data) => {
          console.log(data);
        });
    
    0 讨论(0)
  • 2020-12-15 09:50

    flatMap turns an Observable of Observables into an Observable. It's used in many examples with Promises because often you have an observable and in the map function you want to create a promise for each "item" the observable emmits. Because every fromPromise call creates a new Observable, that makes it an "observable of observables". flatMap reduces that to a "flat" observable.

    In your example you do something different, you turn a single promise into an observable and want to chain it with another observable (also created form a single promise). Concat does what you are looking for, it chains two observables together.

    The error case will work as you would expect.

    0 讨论(0)
  • 2020-12-15 09:57

    If I understood what you are trying to do - you need to create two deferred observables from functions that return promises and concat them:

    var shouldFail = false;
    
    function action1() {
        return new Promise(function (resolve, reject) {    
            console.log('start action1');
            if (shouldFail) {
                reject('reason');
            }
            resolve(true);
        });
    }
    
    function action2() {
        return new Promise(function (resolve, reject) {    
            console.log('start action2');
            resolve(true);
        });
    }
    
    var source1 = Rx.Observable.defer(action1);
    var source2 = Rx.Observable.defer(action2);
    
    var combination = Rx.Observable.concat(source1, source2);
    
    var logObserver = Rx.Observer.create(
    
    function (result) {
        console.log('Next: ' + result);
    },
    
    function (err) {
        console.log('Error: ' + err);
    },
    
    function () {
        console.log('Completed');
    });
    

    then for normal case:

    combination.subscribe(logObserver);
    // start action1
    // Next: true
    // start action2
    // Next: true
    // Completed
    

    And case where fisrt promise fails:

    shouldFail = true;
    combination.subscribe(logObserver);
    // start action1
    // Error: reason
    

    http://jsfiddle.net/cL37tgva/

    0 讨论(0)
提交回复
热议问题