1 | import { Resolve, resolveLater } from '.';
|
2 |
|
3 | export function iterateLater<T>(): [AsyncIterable<T>, Resolve<T>, () => void] {
|
4 | let nextInLine = resolveLater<T>();
|
5 | const queue = [nextInLine];
|
6 | const completed: T = {} as T;
|
7 | const next: Resolve<T> = value => {
|
8 | const [_, resolve] = nextInLine;
|
9 | resolve(value);
|
10 | nextInLine = resolveLater<T>();
|
11 | queue.unshift(nextInLine);
|
12 | };
|
13 | const iterate = async function* () {
|
14 | while (queue.length > 0) {
|
15 | const [nextValue] = queue.pop() as [Promise<T>, Resolve<T>];
|
16 | if ((await nextValue) !== completed) yield nextValue;
|
17 | if (globalThis?.process?.env?.VERBOSE) console.debug(`In queue: ${queue.length}`);
|
18 | }
|
19 | };
|
20 | const complete = () => {
|
21 | const [_, resolve] = nextInLine;
|
22 | resolve(completed);
|
23 | };
|
24 | return [iterate(), next, complete];
|
25 | }
|