1 | import { AsyncIterableX } from './asynciterablex';
|
2 | class RaceAsyncIterable extends AsyncIterableX {
|
3 | constructor(left, right) {
|
4 | super();
|
5 | this._left = left;
|
6 | this._right = right;
|
7 | }
|
8 | async *[Symbol.asyncIterator]() {
|
9 | const leftIt = this._left[Symbol.asyncIterator]();
|
10 | const rightIt = this._right[Symbol.asyncIterator]();
|
11 | let otherIterator;
|
12 | let resultIterator;
|
13 | const { value, done } = await Promise.race([
|
14 | leftIt.next().then(x => {
|
15 | if (!resultIterator) {
|
16 | resultIterator = leftIt;
|
17 | otherIterator = rightIt;
|
18 | }
|
19 | return x;
|
20 | }),
|
21 | rightIt.next().then(x => {
|
22 | if (!resultIterator) {
|
23 | resultIterator = rightIt;
|
24 | otherIterator = leftIt;
|
25 | }
|
26 | return x;
|
27 | })
|
28 | ]);
|
29 | if (!done) {
|
30 | yield value;
|
31 | }
|
32 | otherIterator = otherIterator;
|
33 | resultIterator = resultIterator;
|
34 |
|
35 | if (otherIterator.return) {
|
36 | await otherIterator.return();
|
37 | }
|
38 | let next;
|
39 | while (!(next = await resultIterator.next()).done) {
|
40 | yield next.value;
|
41 | }
|
42 | }
|
43 | }
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 | export function race(left, right) {
|
51 | return new RaceAsyncIterable(left, right);
|
52 | }
|
53 |
|
54 |
|