toPromise

signature: toPromise() : Promise

Convert observable to promise.

toPromise - 图1

Examples

Example 1: Basic Promise

( jsBin |
jsFiddle )

  1. import { of } from 'rxjs/observable/of';
  2. import { toPromise, delay } from 'rxjs/operators';
  3. //return basic observable
  4. const sample = val => of(val).pipe(delay(5000));
  5. //convert basic observable to promise
  6. const example = sample('First Example')
  7. .pipe(toPromise())
  8. //output: 'First Example'
  9. .then(result => {
  10. console.log('From Promise:', result);
  11. });
Example 2: Using Promise.all

( jsBin |
jsFiddle )

  1. import { of } from 'rxjs/observable/of';
  2. import { delay } from 'rxjs/operators';
  3. //return basic observable
  4. const sample = val => of(val).pipe(delay(5000));
  5. /*
  6. convert each to promise and use Promise.all
  7. to wait for all to resolve
  8. */
  9. const example = () => {
  10. return Promise.all([
  11. sample('Promise 1').pipe(toPromise()),
  12. sample('Promise 2').pipe(toPromise())
  13. ]);
  14. };
  15. //output: ["Promise 1", "Promise 2"]
  16. example().then(val => {
  17. console.log('Promise.all Result:', val);
  18. });

Additional Resources


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