I have the following code snippet:
import asyncio
def main():
asyncio.run(work())
print("BEFORE")
async def work():
await asyncio.sleep(1)
print("AFTER")
main()
I would like "BEFORE" to be printed first, followed by "AFTER" however this prints "AFTER" first instead - have I misunderstood how async functions work? I thought that running asyncio.run(...) would allow my code to skip to print("BEFORE") while still running work() in the background.
Ideal output is:
BEFORE
AFTER
Right now it's
AFTER
BEFORE
run seems to be blocking, so you might want to just use gather here:
import asyncio
async def main():
await asyncio.gather(work(), setup())
print('After gather')
async def work():
await asyncio.sleep(2)
print("AFTER")
async def setup():
print("BEFORE")
asyncio.run(main())
This correctly prints
BEFORE
AFTER
After gather
The entire gather statement itself is blocking as well, but all of the functions specified in the gather statement can run asynchronously.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With