2022-05-25

How to get the return value of a task coming from an event loop?

The purpose of this implementation is to be able to call async functions without the "await" keyword
I have a code that is mixing some sync and async functions, I am calling an async function (B) from a sync function (A) inside an event loop and I am unable to get the return value of the async function. An example as follows:

import asyncio
import time


async def B(x):
    print(f'before_delay {x}')
    await asyncio.sleep(1.0)
    print(f'after_delay {x}')
    return x*x

def A(x):
    task = asyncio.create_task(B(x))
    print(task)
    asyncio.get_event_loop().run_until_complete(task) //did not work
    return 0


async def loop_func():
    res = A(9)
    print(f'after calling function {res}')

async def main():
    while True:
        await loop_func()
        await asyncio.sleep(3.0)

asyncio.run(main())

The error I am getting is quite understandable;
RuntimeError: Cannot run the event loop while another loop is running
The problem is that on my program I have a few loop events already running on the background so I cant use asyncio.run() or run_until_complete (or any other low level functions for that matter)
asyncio.wait() would not work as well and also task.done() is never True.
The expected output is:

>>> before_delay 9
>>> after_delay 9 
>>> 81
>>> after calling function 0


No comments:

Post a Comment