toPromise

签名: toPromise() : Promise

将 observable 转换成 promise 。

toPromise - 图1

示例

示例 1: 基础的 Promise

( jsBin |
jsFiddle )

  1. import { of } from 'rxjs/observable/of';
  2. import { toPromise, delay } from 'rxjs/operators';
  3. // 返回基础的 observable
  4. const sample = val => of(val).pipe(delay(5000));
  5. // 将基础的 observable 转换成 promise
  6. const example = sample('First Example')
  7. .pipe(toPromise())
  8. // 输出: 'First Example'
  9. .then(result => {
  10. console.log('From Promise:', result);
  11. });
示例 2: 使用 Promise.all

( jsBin |
jsFiddle )

  1. import { of } from 'rxjs/observable/of';
  2. import { delay } from 'rxjs/operators';
  3. // 返回基础的 observable
  4. const sample = val => of(val).pipe(delay(5000));
  5. /*
  6. 将每个 observable 转换成 promise 并使用 Promise.all
  7. 来等待所有 promise 解析完成
  8. */
  9. const example = () => {
  10. return Promise.all([
  11. sample('Promise 1').pipe(toPromise()),
  12. sample('Promise 2').pipe(toPromise())
  13. ]);
  14. }
  15. // 输出: ["Promise 1", "Promise 2"]
  16. example().then(val => {
  17. console.log('Promise.all Result:', val);
  18. });

其他资源


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