Skip to content

Commit

Permalink
feat(operator): add toPromise operator. closes #159
Browse files Browse the repository at this point in the history
  • Loading branch information
benlesh committed Aug 13, 2015
1 parent 65eb50e commit 361a53b
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 1 deletion.
22 changes: 22 additions & 0 deletions spec/operators/toPromise-spec.js
Original file line number Diff line number Diff line change
@@ -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();
});
});
});
3 changes: 2 additions & 1 deletion src/Observable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,8 @@ export default class Observable<T> {
take: (count: number) => Observable<T>;
takeUntil: (observable: Observable<any>) => Observable<T>;
partition: (predicate: (x: T) => boolean) => Observable<T>[];

toPromise: (PromiseCtor: PromiseConstructor) => Promise<T>;

observeOn: (scheduler: Scheduler, delay?: number) => Observable<T>;
subscribeOn: (scheduler: Scheduler, delay?: number) => Observable<T>;

Expand Down
2 changes: 2 additions & 0 deletions src/Rx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
8 changes: 8 additions & 0 deletions src/operators/toPromise.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import Subscriber from '../Subscriber';

export default function toPromise<T>(PromiseCtor: PromiseConstructor = Promise): Promise<T> {
return new PromiseCtor((resolve, reject) => {
let value: any;
this.subscribe(x => value = x, err => reject(err), () => resolve(value));
});
}

0 comments on commit 361a53b

Please sign in to comment.