我有以下代码:
for await (const part of resolveData(data)) {
console.log({part});
}
它迭代一个异步生成器,如下所示:
const resolveData = async function* <T> (data: SomeValue<T>) {
if (<expression1>) {
if (<expression2>) {
console.log("valid");
yield 1;
}
}
return 2;
}
for wait 循环的输出如下所示:
{ part: 1 }
我也想获得返回值(在本例中为数字 2)。如何获取循环内部或外部的值?
尝试在网上查找但一无所获。
当您在生成器或异步生成器中使用
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>
(遗憾的是,Stack Snippets 中的“JavaScript”面板无法作为模块运行,我想使用顶级
await
,所以我不得不将 JavaScript 放在“HTML”面板中。)
注意如何仅显示
1
。 (for-await-of
也是如此。)
您至少有两个选择:
将
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>
更改代码以直接使用迭代器,而不是使用
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
。