Answer the question
In order to leave comments, you need to log in
Python: How to call an async function from a synchronous one with an active event loop?
There is a function call stack:
[main async func0] -> [sync func1] -> [sync func2] -> [async func3]
from asgiref.sync import async_to_sync
def func2():
result = async_to_sync(func3)()
RuntimeError: You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly.
Answer the question
In order to leave comments, you need to log in
Wrap the asynchronous callback in a synchronous wrapper (maybe a lambda) that calls asyncio.create_task() on the target coroutine, and pass this wrapper as a callback.
If you're in control of func2, it's even easier, put a call to create_task() there.
Now, if you need to wait for the result of the execution, then it will be more difficult - but you can shove the processing of the result into the asynchronous part.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question