【发布时间】:2020-04-26 05:26:56
【问题描述】:
所以我正在尝试创建一个无限的 asyncIterator / 生成器。 该代码应该为“for await of”循环产生“Hello”和“Hi”,然后永远等待下一个值。问题是它不会等待第三个值,也不会在循环后打印 2 并且没有错误地终止。
在节点 v12.14.0 上使用 ts-node 运行。
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);
})();
【问题讨论】:
-
你可以把编译好的js在调试器中单步调试。
-
嗯,我就是这么做的(使用调试器逐步完成)。我无法解释这种行为。 ??????
-
看起来未解决的承诺不会阻止程序退出。
new Promise(() => {}).then(() => console.log('foo'));立即退出。我觉得奇怪的是,只要你继续调用s.send(),程序就会一直运行。也许这是因为一旦你调用s.send(),队列中的一个 Promise 就会解析,所以程序有更多的代码要运行? -
“它不等待第三个值”是什么意思?您的代码中没有第三个值。
标签: javascript node.js typescript asynchronous