Solution Review: Multiple Asynchronous Calls

This lesson will give a detailed review of how to call an asynchronous function multiple times.

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

    1. Create an event loop
       loop = asyncio.get_event_loop()
      
    2. Run async function and wait for completion
       results = loop.run_until_complete(asyncio.gather(
       sum(n1, n2)
       sum(n1, n2)
       sum(n1, n2))
      
      
    3. Close the loop
       loop.close()
      

The following python code explains the concept.

Get hands-on with 1400+ tech skills courses.