Issue
All I need to do is write a simple async function that returns something. Something akin to
async def diss(lis):
x = []
for i in lis:
x.append(i + 1) #the operation is arbitrary, but the input and output of a list is the desired result
return x
lis = [1, 2, 3, 4]
res = await diss(lis)
However, this gives me a syntactical error at await diss(lis)
All I have found online were tutorials where something is printed inside the async function but when trying to return something, I always receive a coroutine or future object.
My goal is to essentially have the loop run asynchronously so to improve performance and then have something returned
Solution
Here you go:
import asyncio
async def diss(lis):
x = []
for i in lis:
x.append(i + 1)
return x
async def main():
lis = [1, 2, 3, 4]
res = await diss(lis)
return res
loop = asyncio.get_event_loop()
res = loop.run_until_complete(main())
print(res)
Make sure you understand why and when to use asyncio in the first place. For example, there's no point to make code above asynchronous.
Usually you only may need asyncio
when you have multiple I/O operations which you can parallelize with asyncio.gather()
.
Answered By - Mikhail Gerasimov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.