Python: Using the result returned by an async function (4 examples)

Updated: August 3, 2023 By: Wolf Post a comment

This pithy, example-based article will walk you through several different ways to use the result returned by an async function in Python.

Using the asyncio.run() function directly

You can call the asyncio.run() function to execute your async function and get the result. This is a simple and convenient way to run a single coroutine and get its result.

The following example uses the aiohttp library to fetch data from a REST API. You can install aiohttp with pip like this:

pip install aiohttp

Or:

pip3 install aiohttp

The code:

# SlingAcademy.com
# This code uses Python 3.11.4

import asyncio
import aiohttp

# create a coroutine to fetch data from the API
async def fetch_data(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

# get the result from the coroutine
result = asyncio.run(fetch_data("https://api.slingacademy.com/"))

# use the result as you wish
print(result)

Output:

{'success': True, 'message': 'Welcome to Sling Academy Public API'}

Await the async function in another async function

This approach uses the await keyword to wait for the async function to finish and get its return value. This can only be done inside another async function.

The example below defines an async function get_data that simulates fetching some data from a remote server and returning it as a dictionary. It also defines another async function process_data that calls get_data using await and prints its return value:

# SlingAcademy.com
# This code uses Python 3.11.4

import asyncio
import random


# Define an async function that returns a value
async def get_data():
    # Simulate some network delay
    await asyncio.sleep(random.random() * 5)
    # Return some data as a string
    return {"status": "success", "message": "Welcome to Sling Academy!"}


# Define another async function that calls the first one using await
async def process_data():
    # Call get_data using await and assign its return value to a variable
    data = await get_data()
    # Use the variable to perform further operations
    print(f"The data is: {data}")

asyncio.run(process_data())

Output:

The data is: {'status': 'success', 'message': 'Welcome to Sling Academy!'}

Using loop.run_until_complete()

You can use the loop.run_until_complete() method to run an async function until it is done and get the result. This is useful if you already have an event loop object and want to run one or more coroutines on it.

Example:

# SlingAcademy.com
# This code uses Python 3.11.4

import asyncio

# mimic a long running task
async def square(number: int) -> int:
    await asyncio.sleep(3)
    return number * number

# create an event loop
loop = asyncio.get_event_loop()

# get the result
result = loop.run_until_complete(square(2023))

# use the result
print(result)  

# close the loop to free up resources
loop.close()

This code will print a number after 3 seconds:

4092529

Using the asyncio.gather() function

The asyncio.gather() function can help you run multiple async functions in parallel and get their results as a list. This is useful if you want to perform concurrent tasks and collect their results at once.

Example:

# SlingAcademy.com
# This code uses Python 3.11.4

import asyncio
import random


# This function will be called by asyncio.gather()
async def square(number: int) -> int:
    await asyncio.sleep(random.randint(1, 5))
    return number * number


# This function will call square() four times
async def do_multiple_tasks():
    return await asyncio.gather(square(10), square(20), square(30), square(40))

# Get the results as a list
result = asyncio.run(do_multiple_tasks())

# Use the results the way you want
print(result)

Output (appears after one or a few seconds):

[100, 400, 900, 1600]

That’s it. Happy coding & have a nice day!