From 361a53befa3d0a1ac4bab5b6690ef4c6ae301628 Mon Sep 17 00:00:00 2001 From: Ben Lesh Date: Wed, 5 Aug 2015 23:49:45 -0700 Subject: [PATCH] feat(operator): add toPromise operator. closes #159 --- spec/operators/toPromise-spec.js | 22 ++++++++++++++++++++++ src/Observable.ts | 3 ++- src/Rx.ts | 2 ++ src/operators/toPromise.ts | 8 ++++++++ 4 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 spec/operators/toPromise-spec.js create mode 100644 src/operators/toPromise.ts diff --git a/spec/operators/toPromise-spec.js b/spec/operators/toPromise-spec.js new file mode 100644 index 0000000000..fc8323503a --- /dev/null +++ b/spec/operators/toPromise-spec.js @@ -0,0 +1,22 @@ +/* globals describe, it, expect */ +var Rx = require('../../dist/cjs/Rx'); +var promise = require('promise'); +var Observable = Rx.Observable; + +describe('Observable.prototype.toPromise()', function () { + it('should convert an Observable to a promise of its last value', function (done) { + Observable.of(1, 2, 3).toPromise(promise).then(function (x) { + expect(x).toBe(3); + done(); + }); + }); + + it('should handle errors properly', function (done) { + Observable.throw('bad').toPromise(promise).then(function () { + throw 'should not be called'; + }, function (err) { + expect(err).toBe('bad'); + done(); + }); + }); +}); \ No newline at end of file diff --git a/src/Observable.ts b/src/Observable.ts index 52bb680a2a..2c9813a1bf 100644 --- a/src/Observable.ts +++ b/src/Observable.ts @@ -129,7 +129,8 @@ export default class Observable { take: (count: number) => Observable; takeUntil: (observable: Observable) => Observable; partition: (predicate: (x: T) => boolean) => Observable[]; - + toPromise: (PromiseCtor: PromiseConstructor) => Promise; + observeOn: (scheduler: Scheduler, delay?: number) => Observable; subscribeOn: (scheduler: Scheduler, delay?: number) => Observable; diff --git a/src/Rx.ts b/src/Rx.ts index da6e2a3ef6..3d82fdaed2 100644 --- a/src/Rx.ts +++ b/src/Rx.ts @@ -122,8 +122,10 @@ observableProto.observeOn = observeOn; observableProto.subscribeOn = subscribeOn; import partition from './operators/partition'; +import toPromise from './operators/toPromise'; observableProto.partition = partition; +observableProto.toPromise = toPromise; import _catch from './operators/catch'; import retryWhen from './operators/retryWhen'; diff --git a/src/operators/toPromise.ts b/src/operators/toPromise.ts new file mode 100644 index 0000000000..b880a32326 --- /dev/null +++ b/src/operators/toPromise.ts @@ -0,0 +1,8 @@ +import Subscriber from '../Subscriber'; + +export default function toPromise(PromiseCtor: PromiseConstructor = Promise): Promise { + return new PromiseCtor((resolve, reject) => { + let value: any; + this.subscribe(x => value = x, err => reject(err), () => resolve(value)); + }); +} \ No newline at end of file