当您在生成器或BLOG生成器中使用return
时,它会在结果对象上设置value
的值,以表示done
为true
.但是for-of
和for-await-of
并不运行结果对象的循环体,其中done
为true.下面是一个简单的例子:
<script type="module">
// Note: Using an async iterator even though we never await
// because the OP's code is async
async function* example() {
yield 1;
return 2;
}
for await (const x of example()) {
console.log(x);
}
</script>
(Sadly, the "JavaScript" panel in Stack Snippets can't be run as a module, and I wanted to use top-level 100, so I had to put the JavaScript in the "HTML" panel instead.)
请注意,只显示了1
个.(for-await-of
也是如此.)
您至少有两个 Select :
1.将return 2
更改为yield 2
,这样生成器在生成2的时候还不会"完成",如下所示:
<script type="module">
// Note: Using an async iterator even though we never await
// because the OP's code is async
async function* example() {
yield 1;
yield 2; // `yield` instead of `return`
}
for await (const x of example()) {
console.log(x);
}
</script>
2.更改代码以直接使用迭代器,而不是使用for-await-of
.
<script type="module">
// Note: Using an async iterator even though we never await
// because the OP's code is async
async function* example() {
yield 1;
return 2;
}
const it = example();
let r;
while (!(r = await it.next()).done) {
console.log(r.value);
}
console.log(r.value);
</script>
在这两种情况下,您现在看到的是1
和2
.