1 | const ARRAY_VALUE = 'value';
|
2 | const ARRAY_ERROR = 'error';
|
3 | export class AsyncSink {
|
4 | constructor() {
|
5 | this._ended = false;
|
6 | this._values = [];
|
7 | this._resolvers = [];
|
8 | }
|
9 | [Symbol.asyncIterator]() {
|
10 | return this;
|
11 | }
|
12 | write(value) {
|
13 | this._push({ type: ARRAY_VALUE, value });
|
14 | }
|
15 | error(error) {
|
16 | this._push({ type: ARRAY_ERROR, error });
|
17 | }
|
18 | _push(item) {
|
19 | if (this._ended) {
|
20 | throw new Error('AsyncSink already ended');
|
21 | }
|
22 | if (this._resolvers.length > 0) {
|
23 | const { resolve, reject } = this._resolvers.shift();
|
24 | if (item.type === ARRAY_ERROR) {
|
25 | reject(item.error);
|
26 | }
|
27 | else {
|
28 | resolve({ done: false, value: item.value });
|
29 | }
|
30 | }
|
31 | else {
|
32 | this._values.push(item);
|
33 | }
|
34 | }
|
35 | next() {
|
36 | if (this._values.length > 0) {
|
37 | const { type, value, error } = this._values.shift();
|
38 | if (type === ARRAY_ERROR) {
|
39 | return Promise.reject(error);
|
40 | }
|
41 | else {
|
42 | return Promise.resolve({ done: false, value });
|
43 | }
|
44 | }
|
45 | if (this._ended) {
|
46 | return Promise.resolve({ done: true });
|
47 | }
|
48 | return new Promise((resolve, reject) => {
|
49 | this._resolvers.push({ resolve, reject });
|
50 | });
|
51 | }
|
52 | end() {
|
53 | while (this._resolvers.length > 0) {
|
54 | this._resolvers.shift().resolve({ done: true });
|
55 | }
|
56 | this._ended = true;
|
57 | }
|
58 | }
|
59 |
|
60 |
|