I need to return a value in async function. I tried to use synchronous form of return:
import asyncio async def main(): for i in range(10): return i await asyncio.sleep(1) print(asyncio.run(main()))
output:
0 [Finished in 204ms]
But it just return value of the first loop, which is not expexted. So changed the code as below:
import asyncio async def main(): for i in range(10): yield i await asyncio.sleep(1) for _ in main(): print(_)
output:
TypeError: 'async_generator' object is not iterable
by using async generator I am facing with this error. How can I return a value for every loop of async function?
Thanks
Advertisement
Answer
You need to use an async for
which itself needs to be inside an async
function:
async def get_result(): async for i in main(): print(i) asyncio.run(get_result())