0
from asyncio import Future
import asyncio

async def plan_fut(future_obj):
    print('future started')
    await asyncio.sleep(1)
    future_obj.set_result('Future completes')

def create() -> Future:
    future_obj = Future()
    asyncio.create_task(plan_fut(future_obj))
    return future_obj

async def main():
    future_obj = create()
    result = await future_obj

    print(result)

asyncio.run(main())

Result

future started
Future completes

If I change function create to

async def create() -> Future:
    future_obj = Future()
    asyncio.create_task(plan_fut(future_obj))
    return future_obj

result is

<Future pending>
future started
  1. I understand the case 1 where create is blocking and main awaits for future object
  2. I don't understand the case 2, when create is async, why does main behave weird, shouldn't it wait for future to complete in this case as well?
Pramod
  • 371
  • 4
  • 13
  • Every `async` or future needs one corresponding `await`. In your second case you first need to `await` the `async` function, before you get the future, which you then also need to `await`. – deceze Jan 16 '23 at 13:33
  • Thanks @deceze , that fixes the issue: ``` future_obj = await create() ``` – Pramod Jan 16 '23 at 13:44

0 Answers0