I need to return a value in async function. I tried to use synchronous form of return:
JavaScript
x
9
1
import asyncio
2
3
async def main():
4
for i in range(10):
5
return i
6
await asyncio.sleep(1)
7
8
print(asyncio.run(main()))
9
output:
0 [Finished in 204ms]
But it just return value of the first loop, which is not expexted. So changed the code as below:
JavaScript
1
10
10
1
import asyncio
2
3
async def main():
4
for i in range(10):
5
yield i
6
await asyncio.sleep(1)
7
8
for _ in main():
9
print(_)
10
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:
JavaScript
1
6
1
async def get_result():
2
async for i in main():
3
print(i)
4
5
asyncio.run(get_result())
6