擅长:python、mysql、java
<blockquote>
<p>I'm trying to write a simple asynchronous data batch generator, but having troubles with understanding how to yield from an async for loop</p>
</blockquote>
<p>从<code>async for</code>获得的结果与常规收益类似,只是它还必须由<code>async for</code>或等效物收集。例如,<code>get_docs</code>中的<code>yield</code>使其成为异步生成器。如果将<code>print(res)</code>替换为<code>main()</code>中的<code>yield res</code>,那么{<cd7>}也将成为一个异步生成器。在</p>
<blockquote>
<p>the generator in <code>main()</code> should exhaust in <code>gen_batches()</code>, so I can gather <em>all</em> results in <code>gen_batches()</code></p>
</blockquote>
<p>要收集由异步生成器生成的值(例如用<code>print(res)</code>替换为<code>yield res</code>)的{<cd7>},可以使用helper协同例程:</p>
<pre><code>def gen_batches(self):
loop = asyncio.get_event_loop()
async def collect():
return [item async for item in self.main()]
items = loop.run_until_complete(collect())
loop.close()
return items
</code></pre>
<p><code>collect()</code>助手使用了<a href="https://www.python.org/dev/peps/pep-0530/" rel="nofollow noreferrer">PEP 530</a>异步理解,可以将其视为更显式的语法糖分:</p>
^{pr2}$