javascript - Chaining promises with RxJS -


i'm new rxjs , frp in general. had idea of converting existing promise chain in expressjs application observable practice. aware isn't best example maybe can shed light.

what i'm trying do:

  1. i have 2 promises - prom1 , prom2
  2. i want prom1 run before prom2
  3. if prom1 sends reject(err), want cancel prom2 before starts.
  4. i want error message prom1 returns available onerror method on observer.

var prom1 = new promise(function(resolve, reject) {     if (true) {        reject('reason');     }     resolve(true); });  var prom2 = new promise(function(resolve, reject) {     resolve(true); });  // do here? i've tried far... var source1 = rx.observable.frompromise(prom1); var source2 = source1.flatmap(rx.observable.frompromise(prom2));  var subscription = source2.subscribe(     function (result) { console.log('next: ' + result); },      // want error 'reason' made available here     function (err) { console.log('error: ' + err); },      function () { console.log('completed'); }); 

if understood trying - need create 2 deferred observables functions return promises , 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 normal case:

combination.subscribe(logobserver); // start action1 // next: true // start action2 // next: true // completed 

and case fisrt promise fails:

shouldfail = true; combination.subscribe(logobserver); // start action1 // error: reason 

http://jsfiddle.net/cl37tgva/


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -