Skip to content

Commit 7067ee1

Browse files
authored
Improve concurrency in URL fetching
Refactor URL fetching to use asyncio.wait for better concurrency management.
1 parent 75ecfe9 commit 7067ee1

1 file changed

Lines changed: 13 additions & 7 deletions

File tree

utilities/Typing-Speed-Tester/Typing-Speed-Tester.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,13 +48,19 @@ async def fetch_phrase_async():
4848
"https://api.quotable.io/random"
4949
]
5050
async with aiohttp.ClientSession() as session:
51-
tasks = [fetch_url(session, url) for url in urls]
52-
# Gather them concurrently
53-
results = await asyncio.gather(*tasks)
54-
for res in results:
55-
if res:
56-
return res
57-
return None
51+
tasks = {asyncio.create_task(fetch_url(session, url)) for url in urls}
52+
53+
while tasks:
54+
done, tasks = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
55+
for task in done:
56+
result = task.result()
57+
if result:
58+
# Cancel remaining tasks — we got what we need
59+
for t in tasks:
60+
t.cancel()
61+
return result
62+
63+
return None
5864

5965

6066
def main():

0 commit comments

Comments
 (0)