<@ULVA73B9P>, how can I using async functions and ...
# ask-marvin
p
@Marvin, how can I using async functions and have wait for one of either two functions to return before proceeding?
m
To wait for one of two asynchronous functions to return before proceeding in Prefect 3.x, you can use Python's
asyncio
library, which supports asynchronous programming. Specifically,
asyncio.wait
can be used to wait for one or more coroutines to complete. Here's a basic pattern you can follow:
Copy code
python
import asyncio

async def function_one():
    # Simulate some work with a sleep
    await asyncio.sleep(2)
    return 'Function One Completed'

async def function_two():
    # Simulate some work with a sleep
    await asyncio.sleep(1)
    return 'Function Two Completed'

async def main():
    # Schedule the tasks
    tasks = [function_one(), function_two()]

    # Wait for the first task to complete
    done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)

    # Process the results of the completed task
    for task in done:
        print(task.result())

    # Optionally, cancel pending tasks if needed
    for task in pending:
        task.cancel()

# Run the main function
asyncio.run(main())
This example demonstrates how to wait for the first of two functions to complete using
asyncio.wait
with the
return_when=asyncio.FIRST_COMPLETED
parameter. This approach is useful when you're working with Prefect's asynchronous tasks, which follow standard async Python behavior. For more on asynchronous functions in Prefect, you can check out their documentation on writing tasks.