1 | import { identity, identityAsync } from '../util/identity';
|
2 |
|
3 | const NEVER_PROMISE = new Promise(() => { });
|
4 | function wrapPromiseWithIndex(promise, index) {
|
5 | return promise.then(value => ({ value, index }));
|
6 | }
|
7 |
|
8 | export async function forkJoin(...sources) {
|
9 | let fn = (sources.shift() || identityAsync);
|
10 | if (fn && typeof fn !== 'function') {
|
11 | sources.unshift(fn);
|
12 | fn = identityAsync;
|
13 | }
|
14 | const length = sources.length;
|
15 | const iterators = new Array(length);
|
16 | const nexts = new Array(length);
|
17 | let active = length;
|
18 | const values = new Array(length);
|
19 | const hasValues = new Array(length);
|
20 | hasValues.fill(false);
|
21 | for (let i = 0; i < length; i++) {
|
22 | const iterator = sources[i][Symbol.asyncIterator]();
|
23 | iterators[i] = iterator;
|
24 | nexts[i] = wrapPromiseWithIndex(iterator.next(), i);
|
25 | }
|
26 | while (active > 0) {
|
27 | const next = Promise.race(nexts);
|
28 | const { value: next$, index } = await next;
|
29 | if (next$.done) {
|
30 | nexts[index] = NEVER_PROMISE;
|
31 | active--;
|
32 | }
|
33 | else {
|
34 | const iterator$ = iterators[index];
|
35 | nexts[index] = wrapPromiseWithIndex(iterator$.next(), index);
|
36 | hasValues[index] = true;
|
37 | values[index] = next$.value;
|
38 | }
|
39 | }
|
40 | if (hasValues.length > 0 && hasValues.every(identity)) {
|
41 | return await fn(values);
|
42 | }
|
43 | return undefined;
|
44 | }
|
45 |
|
46 |
|