0
import asyncio

async def f():
    # something, for example await asyncio.sleep(4)
    return "return value from f"

async def main():
    # schedule f, print result, but don't await
    for i in range(10):
        await asyncio.sleep(1)  # just an example for some other task
        print(i)

asyncio.run(main())

I could use print(await f()) but that blocks due to await. I want print to be called as a "callback function" after f() has returned while the rest of main() has already continued. So, assuming that # something in f took 4 seconds, the expected output would look like this:

0
1
2
3
return value from f
4
5
6
7
8
9
1
  • 1
    You probably have a few options. add_done_callback, gather, and as_completed come to mind. Without knowing more specifics, though, it's hard to say which will work best. Commented Jul 12, 2021 at 16:42

2 Answers 2

1

You can define a function that takes f and a callback function as parameters.

async def call(f, cb):
    cb(await f())

And you can schedule a task for it without using await:

asyncio.create_task(call(f, print))
Sign up to request clarification or add additional context in comments.

Comments

0

Does this work for you? I changed the f() coroutine a little bit but this does seem to work. Also, you need to await asyncio.sleep(). Let me know what you think or if you have any questions.

Here's the answer that I referenced: How I call an async function without await?

import asyncio

async def f():
    await asyncio.sleep(3)
    print("return value from f")

async def main():
    loop = asyncio.get_event_loop()
    loop.create_task(f())
    for i in range(10):
        await asyncio.sleep(1)  # just an example for some other task
        print(i)

asyncio.run(main())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.