Jake
Jake

Reputation: 537

How to get the following output in asyncio gather

Is there a way I can get the as_completed results for both result1 and result2 combined?

Expected Output

[0, 0, 1, 1, 2, 2]

Current Output

[0, 1, 2, 0, 1, 2]

Code

import asyncio

async def sleep(i):
    await asyncio.sleep(i)
    return i

async def main():
    result1 = [sleep(i) for i in [2, 1, 0]]
    result2 = [sleep(i) for i in [2, 1, 0]]

    result1Gathered = asyncio.as_completed(result1)
    result2Gathered = asyncio.as_completed(result2)

    result = await asyncio.gather(*result1Gathered, *result2Gathered)

    print(result)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

Upvotes: 2

Views: 662

Answers (1)

Jab
Jab

Reputation: 27515

This is because gather returns the results as given to it.

What you want is not gather but to just loop through the results of as_completed. You can use itertools.chain to combine all the iterables:

from itertools import chain

...

async def main():
    result1 = [sleep(i) for i in [2, 1, 0]]
    result2 = [sleep(i) for i in [2, 1, 0]]

    result = [await i for i in asyncio.as_completed(chain(result1, result2))]

    print(result)

Result:

[0, 0, 1, 1, 2, 2]

Upvotes: 4

Related Questions