如何从异步函数返回常规(非异步)生成器?
async def foo():
list = await stuff() # expensive io bound here and done.
for i in list:
yield i, i*2
for i, j in await foo():
# regular loop over i and j using the regular generator
这个有用吗?
我猜您正在寻找
async for
来实现您想要的输出。
foo()
是一个异步生成器,您可以通过async for
迭代它。在第await stuff()
行的第一次迭代中,它将控制权交还给事件循环,让他运行其他任务,当准备好时,事件循环将执行其余任务,直到它到达yield i, i*2
并将该元组提供给您的外循环。直到最后,它将迭代 list
并生成该元组。