Issue
I have code that sequentially runs asynchronous functions, which in turn make asynchronous requests. How can I run these functions in parallel?
for i in get_functions_list:
try:
all_data.append(i)
except:
continue
Now the functions are executed sequentially and it takes about 50 seconds, I want to reduce that time
Solution
You just need to use the asyncio.gather
method to collect all the async
functions and then run them concurrently.
Here is the some example code that will achieve this:
import asyncio
async def func1():
print('func1 started')
await asyncio.sleep(1)
print('func1 finished')
async def func2():
print('func2 started')
await asyncio.sleep(2)
print('func2 finished')
async def main():
await asyncio.gather(
func1(),
func2()
)
asyncio.run(main())
The code will return this:
func1 started
func2 started
func1 finished
func2 finished
Answered By - darren lefcoe
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.