UNPKG

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