Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set Async Create Task to two Variables

I’m repurposing some synchronous python code to be asynchronous. It is working really well, but when I change this line of code

    l = asyncio.create_task(Functions.getData(session, id))

to this

    l, i = asyncio.create_task(Functions.getData(session, id))

I get a RuntimeError that says this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"Exception has occurred: RuntimeError
await wasn't used with future
  File 'test.py', line 46, in get_tasks
    l, i = asyncio.create_task(Functions.getData(session, id))
    ^^^^
  File 'test.py', line 79, in get_data
    a, b, c = get_tasks(session)
                               ^^^^^^^^^^^^^^^^^^
  File 'test.py', line 108, in <module>
    asyncio.run(get_data())
RuntimeError: await wasn't used with future"

My getData function returns a tuple (var1, var2), but for some reason asyncio does not like it.

>Solution :

The issue is that when you use asyncio.create_task, it returns a single future object representing the task. If you want to unpack multiple values from the result of Functions.getData, you should do it after awaiting the task.

import asyncio

async def get_data(session, id):
    # Simulating some asynchronous operation
    await asyncio.sleep(1)
    return "result1", "result2"

async def get_tasks(session, id):
    task = asyncio.create_task(get_data(session, id))
    result = await task  # Wait for the task to complete
    var1, var2 = result
    return var1, var2

async def main():
    session = None  # Replace with your session
    id = 123  # Replace with your id
    var1, var2 = await get_tasks(session, id)
    print(var1, var2)

asyncio.run(main())

This way, you await the task and then unpack the results

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading