Hello folks :wave: does anyone has suggestions on...
# ask-community
t
Hello folks 👋 does anyone has suggestions on how to run async functions in Prefect v3 sync flows? We’re using a library that has only async functions and our flows are built over sync calls
n
I just use
asyncio.run()
t
interesting… a coworker vibe coded this, but
asyncio.run()
is way simpler:
Copy code
def run_async_threadsafe(coro: Coroutine[Any, Any, T]) -> T:
    """Run an async coroutine from sync code, handling existing event loops.

    Args:
        coro: A coroutine object to run

    Returns:
        The result of the coroutine execution

    Raises:
        Any exception raised by the coroutine
    """
    try:
        # re-use existing event loop
        running_loop = asyncio.get_running_loop()
        future = asyncio.run_coroutine_threadsafe(coro, running_loop)
        return future.result()
    except RuntimeError:
        # no existing event loop, use a new one
        loop = asyncio.new_event_loop()
        thread = threading.Thread(target=run_event_loop, args=(loop,), daemon=True)
        thread.start()
        future = asyncio.run_coroutine_threadsafe(coro, loop)
        return future.result()
n
yeah I think this is basically what run() does for you
t
yeah… we can’t trust entirely on LLMs 😅 Thanks for the answer 🙏
👍 1