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](), rightIt = this._right[Symbol.asyncIterator]();
|
10 | let otherIterator;
|
11 | let resultIterator;
|
12 | const { value, done } = await Promise.race([
|
13 | leftIt.next().then(x => {
|
14 | if (!resultIterator) {
|
15 | resultIterator = leftIt;
|
16 | otherIterator = rightIt;
|
17 | }
|
18 | return x;
|
19 | }),
|
20 | rightIt.next().then(x => {
|
21 | if (!resultIterator) {
|
22 | resultIterator = rightIt;
|
23 | otherIterator = leftIt;
|
24 | }
|
25 | return x;
|
26 | })
|
27 | ]);
|
28 | if (!done) {
|
29 | yield value;
|
30 | }
|
31 | otherIterator = otherIterator;
|
32 | resultIterator = resultIterator;
|
33 |
|
34 | if (otherIterator.return) {
|
35 | await otherIterator.return();
|
36 | }
|
37 | let next;
|
38 | while (!(next = await resultIterator.next()).done) {
|
39 | yield next.value;
|
40 | }
|
41 | }
|
42 | }
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 | export function race(left, right) {
|
50 | return new RaceAsyncIterable(left, right);
|
51 | }
|
52 |
|
53 |
|