UNPKG

@reactivex/ix-esnext-esm

Version:

The Interactive Extensions for JavaScript

47 lines (45 loc) 1.57 kB
import { identity, identityAsync } from '../util/identity'; // eslint-disable-next-line @typescript-eslint/no-empty-function const NEVER_PROMISE = new Promise(() => { }); function wrapPromiseWithIndex(promise, index) { return promise.then(value => ({ value, index })); } // eslint-disable-next-line complexity export async function forkJoin(...sources) { let fn = (sources.shift() || identityAsync); if (fn && typeof fn !== 'function') { sources.unshift(fn); fn = identityAsync; } const length = sources.length; const iterators = new Array(length); const nexts = new Array(length); let active = length; const values = new Array(length); const hasValues = new Array(length); hasValues.fill(false); for (let i = 0; i < length; i++) { const iterator = sources[i][Symbol.asyncIterator](); iterators[i] = iterator; nexts[i] = wrapPromiseWithIndex(iterator.next(), i); } while (active > 0) { const next = Promise.race(nexts); const { value: next$, index } = await next; if (next$.done) { nexts[index] = NEVER_PROMISE; active--; } else { const iterator$ = iterators[index]; nexts[index] = wrapPromiseWithIndex(iterator$.next(), index); hasValues[index] = true; values[index] = next$.value; } } if (hasValues.length > 0 && hasValues.every(identity)) { return await fn(values); } return undefined; } //# sourceMappingURL=forkjoin.mjs.map