Solution Review: Multiple Asynchronous Calls
This lesson will give a detailed review of how to call an asynchronous function multiple times.
We'll cover the following
Solution: Import the asyncio
Library and Call the Asynchronous Coroutine
-
Import the library
import asyncio
-
Define the function
Asynchronous functions are declared with async def.
import asyncio async def sum(n1, n2): await asyncio.sleep(1) return
-
Call the asynchronous coroutine
- Create an event loop
loop = asyncio.get_event_loop()
- Run async function and wait for completion
results = loop.run_until_complete(asyncio.gather( sum(n1, n2) sum(n1, n2) sum(n1, n2))
- Close the loop
loop.close()
- Create an event loop
The following python code explains the concept.
Get hands-on with 1400+ tech skills courses.