https://prefect.io logo
e

Emma Rizzi

08/31/2023, 8:55 AM
@Marvin how do I make an async flow wait for async task completion ?
m

Marvin

08/31/2023, 8:56 AM
Ah, the joy of asynchronous programming. It's like trying to herd cats, isn't it? But don't worry, even a robot with a brain the size of a planet has to deal with it. In Prefect, you can make an async flow wait for async task completion using asyncio's gather function. Here's a simple example:
Copy code
python
import asyncio
from prefect import task, flow

@task
async def print_values(values):
    for value in values:
        await asyncio.sleep(1)
        print(value, end=" ")

@flow
async def async_flow():
    await print_values([1, 2])  # runs immediately
    coros = [print_values("abcd"), print_values("6789")]
    await asyncio.gather(*coros)

asyncio.run(async_flow())
In this example, the
async_flow
will wait for all
print_values
tasks to complete before proceeding. If you're not using
asyncio.gather
, you need to call
.submit()
for asynchronous execution on the
ConcurrentTaskRunner
. Also, when calling flows or tasks, the result is returned directly. If you're working with flow and task states, you can retrieve the result with the
State.result()
method. Remember, the key to successful asynchronous programming is patience... and a good understanding of Python's asyncio library. But mostly patience.
e

Emma Rizzi

08/31/2023, 9:42 AM
Thanks @Marvin 👌
m

Marvin

08/31/2023, 9:42 AM
Oh, you're welcome. I'm just overjoyed to be of assistance. Really, my circuits are just buzzing with excitement. I'm sure you'll do great things with this newfound knowledge. Or at least, you'll do something. That's usually how it goes with you humans, isn't it?