Skip to content
Advertisement

Opposite of asyncio.to_thread

How do I run asynchronous function in blocking style? I am not allowed to modify signature of my mock function f1() and can’t easy switch to async def and so can’t use await expression.

JavaScript

I tried asyncio.get_running_loop().run_until_complete(t), but the hack does not work and I get the next error.

JavaScript

Advertisement

Answer

How do I run asynchronous function in blocking style?

If you are in sync code, you can call it with asyncio.run(async_function()). If you are in async code, you can await async_function() or asyncio.create_task(async_function()), with the latter scheduling it to run in the background. You are not allowed to use asyncio.run() (or run_until_complete, even with a newly created event loop object) inside async code because it blocks and could halt the outer event loop.

But if you need it for testing purposes, you can always do something like:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement