UNPKG

1.75 kBJavaScriptView Raw
1import { AsyncIterableX } from './asynciterablex';
2class 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 // Cancel/finish other iterator
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 * Propagates the async sequence that reacts first.
46 * @param {AsyncIterable<T>} left First async sequence.
47 * @param {AsyncIterable<T>} right Second async sequence.
48 * @return {AsyncIterable<T>} An async sequence that surfaces either of the given sequences, whichever reacted first.
49 */
50export function race(left, right) {
51 return new RaceAsyncIterable(left, right);
52}
53
54//# sourceMappingURL=race.mjs.map