Skip to content Skip to sidebar Skip to footer

How To Use An Async For Loop To Iterate Over A List?

So I need to call an async function for all items in a list. This could be a list of URLs and an async function using aiohttp that gets a response back from every URL. Now obviousl

Solution 1:

Use asyncio.as_completed:

for future in asyncio.as_completed(map(fetch, urls)):
    result = await future

Or asyncio.gather:

results = await asyncio.gather(map(fetch, urls))

EDIT: If you don't mind having an external dependency, you can use aiostream.stream.map:

from aiostream import stream, pipe

asyncdeffetch_many(urls):
    xs = stream.iterate(urls) | pipe.map(fetch, ordered=True, task_limit=10)
    asyncfor result in xs:
        print(result)

You can control the amount of fetch coroutine running concurrently using the task_limit argument, and choose whether to get the results in order, or as soon as possible.

See more examples in this demonstration and the documentation.

Disclaimer: I am the project maintainer.

Solution 2:

Please note, that Vincents answer has a partial problem: You must have a splatter operator infront of the map function, otherwise asyncio.gather would try to use the list as whole. So do it like this:

results = await asyncio.gather(*map(fetch, url))

Post a Comment for "How To Use An Async For Loop To Iterate Over A List?"