Skip to content
This repository has been archived by the owner on Dec 16, 2020. It is now read-only.

Commit

Permalink
feat: move toPromise to prototype
Browse files Browse the repository at this point in the history
Calling from the prototype makes more sense than having to wrap a
stream.

Deprecates the `.toPromise(stream)` method.
  • Loading branch information
trs committed Jul 11, 2019
1 parent 6fb844d commit 6ffd790
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 9 deletions.
4 changes: 2 additions & 2 deletions src/PureStream.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ describe('PureStream', () => {
});

describe('wrap', () => {
it('wraps native stream', (done) => {
it('wraps node stream', (done) => {
const source = new PassThrough({ objectMode: true });
const dest = new PureStream();

Expand All @@ -77,7 +77,7 @@ describe('PureStream', () => {
source.destroy(new Error('test'));
});

it('wraps native stream with multiple errors', (done) => {
it('wraps node stream with multiple errors', (done) => {
const source = new PassThrough({ objectMode: true });
const dest = new PureStream();

Expand Down
12 changes: 12 additions & 0 deletions src/PureStream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,18 @@ export class PureStream<In, Out = In> {
return stream;
}

/** Convert this PureStream into a promise for an array of each value in the stream */
public toPromise() {
return new Promise<Out[]>((resolve, reject) => {
const accumulated: Out[] = [];

this.each((value) => accumulated.push(value)).done((err) => {
if (err) reject(err);
else resolve(accumulated);
});
});
}

public static wrap<T>(source: Readable): PureStream<T>;
public static wrap<T>(source: PassThrough): PureStream<T>;
public static wrap<In, Out>(source: Transform): PureStream<In, Out>;
Expand Down
22 changes: 15 additions & 7 deletions src/methods/to.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,27 @@
import { reduce } from "./reduce";
import { PureStream } from "../PureStream";
import { reduce } from './reduce';
import { PureStream } from '../PureStream';

/**
* Convert a stream into a promise for an array of values.
* This consumes the stream.
*/
export function toPromise<In, Out = In>(stream: PureStream<In, Out>) {
// eslint-disable-next-line no-console
console.trace(
'Call to deprecated method `toPromise(stream)`; please use `PureStream.prototype.toPromise()`'
);

return new Promise<Out[]>((resolve, reject) => {
stream.pipe(reduce<Out, Out[]>(async (prev, next) => {
prev.push(next);
return prev;
}, []))
stream
.pipe(
reduce<Out, Out[]>(async (prev, next) => {
prev.push(next);
return prev;
}, [])
)
.each(resolve)
.done((err) => {
if (err) reject(err);
})
});
});
}

0 comments on commit 6ffd790

Please # to comment.