So I am trying to create an infinite asyncIterator / generator. The code is supposed to yield "Hello" and "Hi" to the 'for await of' loop and then wait forever for next value. The problem is that it does not wait for the third value nor prints 2 after loop and terminates without errors.
Running with ts-node on Node v12.14.0.
class Source<T> {
_data: T[] = [];
_queue: ((val: T) => void)[] = [];
send(val: T) {
if (this._queue.length > 0) {
this._queue.shift()!(val);
} else {
this._data.push(val);
}
}
next(): Promise<{ done: boolean, value: T }> {
return new Promise((resolve, _reject) => {
if (this._data.length > 0) {
resolve({ done: false, value: this._data.shift()! });
} else {
this._queue.push(value => resolve({ done: false, value }));
}
});
}
[Symbol.asyncIterator]() {
return this;
}
}
(async () => {
const s = new Source<String>();
s.send("Hello");
s.send("Hi");
console.log(1);
for await (let str of s) {
console.log(str);
}
console.log(2);
})();