Concurrent Execution with asyncio.gather()
`asyncio.gather(*coros)` fires multiple coroutines concurrently on the event loop and returns an ordered list of their results when all have resolved 🤹.
import asyncio
async def fetch_stock(ticker):
await asyncio.sleep(0.01)
return f"{ticker}: OK"
async def main():
results = await asyncio.gather(
fetch_stock("AAPL"),
fetch_stock("NVDA"),
fetch_stock("GOOG")
)
return results
print(asyncio.run(main())) # ['AAPL: OK', 'NVDA: OK', 'GOOG: OK'] 🤹
# 46. Concurrent Execution with asyncio.gather() `asyncio.gather(*coros)` fires multiple coroutines concurrently on the event loop and returns an ordered list of their results when all have resolved 🤹. ```python import asyncio async def fetch_stock(ticker): await asyncio.sleep(0.01) return f"{ticker}: OK" async def main(): results = await asyncio.gather( fetch_stock("AAPL"), fetch_stock("NVDA"), fetch_stock("GOOG") ) return results print(asyncio.run(main())) # ['AAPL: OK', 'NVDA: OK', 'GOOG: OK'] 🤹 ``` Even if `NVDA` finishes before `AAPL`, `asyncio.gather` preserves the exact input order in the final result list! 🤹 --- ### Question In what order does `asyncio.gather()` return its results? 🧠- [ ] a. In the exact order coroutines were passed into `gather` 🤹 - [ ] b. Randomly based on network packet arrival speed - [ ] c. Sorted alphabetically by returned string value - [ ] d. Reversed from finish order --- ### Challenge Write an async function `square_async(n)` returning `n * n`. In `main()`, use `await asyncio.gather(square_async(2), square_async(3), square_async(4))` and return the list. Run and print. 🎯 <details> <summary>Solution</summary> ```python import asyncio async def square_async(n): return n * n async def main(): return await asyncio.gather( square_async(2), square_async(3), square_async(4) ) print(asyncio.run(main())) ``` </details>