Quantcast
Channel: How can I call an async function without await? - Stack Overflow
Viewing all articles
Browse latest Browse all 7

Answer by freakish for How can I call an async function without await?

$
0
0

One way would be to use create_task function:

import asyncioasync def handler_message(request):    ...    loop = asyncio.get_event_loop()    loop.create_task(perform_message(x,y,z))    ...

As per the loop documentation, starting Python 3.10, asyncio.get_event_loop() is deprecated. If you're trying to get a loop instance from a coroutine/callback, you should use asyncio.get_running_loop() instead. This method will not work if called from the main thread, in which case a new loop must be instantiated:

loop = asyncio.new_event_loop()asyncio.set_event_loop(loop)loop.create_task(perform_message(x, y, z))loop.run_forever()

Furthermore, if the call is only made once throughout your program's runtime and no other loop needs to be is instantiated (unlikely), you may use:

asyncio.run(perform_message(x, y, z))

This function creates an event loop and terminates it once the coroutine ends, therefore should only be used in the aforementioned scenario.


Viewing all articles
Browse latest Browse all 7


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>