Skip to content

Latest commit

 

History

History
63 lines (47 loc) · 2.08 KB

frompromise.md

File metadata and controls

63 lines (47 loc) · 2.08 KB

fromPromise

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

Create observable from promise, emitting result.


💡 Flattening operators can accept promises without wrapping!

💡 You could also use from for the same result!


Examples

Example 1: Converting promise to observable and catching errors

( jsBin | jsFiddle )

import { of } from 'rxjs/observable/of';
import { fromPromise } from 'rxjs/observable/fromPromise';
import { mergeMap, catchError } from 'rxjs/operators';

//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 = of(true, false);
const example = source.pipe(
  mergeMap(val =>
    fromPromise(myPromise(val)).pipe(
      //catch and gracefully handle rejections
      catchError(error => 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/internal/observable/fromPromise.ts