Skip to content

Latest commit

 

History

History
56 lines (42 loc) · 1.83 KB

frompromise.md

File metadata and controls

56 lines (42 loc) · 1.83 KB

fromPromise

signature: fromPromise(promise: Promise, scheduler: Scheduler): Observable

Create observable from promise, emitting result.


💡 Flattening operators can generally accept promises without wrapping!

💡 You could also use Observable.from for the same result!


Examples

Example 1: Converting promise to observable and catching errors

( jsBin | jsFiddle )

//example promise that will resolve or reject based on input
const myPromise = willReject => {
  return new Promise((resolve, reject) => {
    if (willReject) {
      reject('Rejected!');
    }
    resolve('Resolved!');
  });
};
//emit true, then false
const source = Rx.Observable.of(true, false);
const example = source.mergeMap(val =>
  Rx.Observable
    //turn promise into observable
    .fromPromise(myPromise(val))
    //catch and gracefully handle rejections
    .catch(error => Rx.Observable.of(`Error: ${error}`))
);
//output: 'Error: Rejected!', 'Resolved!'
const subscribe = example.subscribe(val => console.log(val));

Additional Resources


📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/observable/PromiseObservable.ts