fromPromise

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

Create observable from promise, emitting result.


:bulb: Flattening operators can generally accept promises without wrapping!

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


fromPromise - 图3

Examples

Example 1: Converting promise to observable and catching errors

( jsBin |
jsFiddle )

  1. import { of } from 'rxjs/observable/of';
  2. import { fromPromise } from 'rxjs/observable/fromPromise';
  3. import { mergeMap, catchError } from 'rxjs/operators';
  4. //example promise that will resolve or reject based on input
  5. const myPromise = willReject => {
  6. return new Promise((resolve, reject) => {
  7. if (willReject) {
  8. reject('Rejected!');
  9. }
  10. resolve('Resolved!');
  11. });
  12. };
  13. //emit true, then false
  14. const source = of(true, false);
  15. const example = source.pipe(
  16. mergeMap(val =>
  17. fromPromise(myPromise(val)).pipe(
  18. //catch and gracefully handle rejections
  19. catchError(error => of(`Error: ${error}`))
  20. )
  21. )
  22. );
  23. //output: 'Error: Rejected!', 'Resolved!'
  24. const subscribe = example.subscribe(val => console.log(val));

Additional Resources


:file_folder: Source Code:
https://github.com/ReactiveX/rxjs/blob/master/src/internal/observable/fromPromise.ts