Функция asyncio.wait() это еще один способ вызвать множество асинхронных задач.
Она работает в нескольких режимах.
1. Самый простой - ждем завершения всех задач
async def main():
tasks = [asyncio.create_task(do_it(i)) for i in range(10)]
done, pending = await asyncio.wait(
tasks,
return_when=asyncio.ALL_COMPLETED
)
for task in done:
try:
print(task.result())
except Exception as e:
print(e)
Очень похоже на gather, но работает не так.
▫️возвращает не результаты, а два сета с объектами Task у которых можно забрать результат через task.result() если они в списке done
▫️не гарантирует порядок результатов так как оба объекта это set
▫️не выбрасывает исключение когда оно появляется, а сохраняет его в Task. Исключение появится когда попробуете забрать резултьтат.
2. Ждем завершения первой задачи, даже если там ошибка.
async def main():
tasks = [asyncio.create_task(do_it(i)) for i in range(3)]
done, pending = await asyncio.wait(
tasks,
return_when=asyncio.FIRST_COMPLETED
)
# в done может быть несколько задач!
for task in done:
try:
print(task.result())
except Exception as e:
print(f"Fail: {e}")
# Оставшиеся задачи в pending, как правило, нужно отменить, иначе они будут продолжать работать
for task in pending:
task.cancel()
В сете done будут таски которые успели завершится, причем как успешно так и нет.
3. До первой ошибки.
Тоже самое, но с аргументом FIRST_EXCEPTION
done, pending = await asyncio.wait(
tasks,
return_when=asyncio.FIRST_EXCEPTION
)
Функция завершается как только первая задача упадет с ошибкой.
Учтите, что в любом случае done вы можете обранужить несколько задач, как с ошибками так и успешные.
↗️ Полный листинг примеров здесь
#async
🌍 In 2023, explorers finished mapping over 75% of the world’s seafloor in high detail, uncovering thousands of undersea mountains and canyons hidden beneath the oceans. ✨
#exploration⚡#mapping⚡#discovery⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Over 80% of Earth’s ocean remains unmapped and unexplored by humans. Modern sonar and robotic submersibles are revealing new mountains, trenches, and species with every deep-sea journey. ✨
#exploration⚡#ocean⚡#discovery⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The first map to show the Americas as a separate continent was made by German cartographer Martin Waldseemüller in 1507. It’s where the name “America” first appeared on a world map. ✨
#cartography⚡#history⚡#discovery⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 In 2022, explorers used sonar to map a hidden undersea volcano off Madagascar’s coast, revealing a peak 800 meters tall that was completely unknown before their expedition. ✨
#exploration⚡#discovery⚡#oceans⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌎 While mapping the ocean floor in 1947, researchers aboard HMS Challenger discovered the Mid-Atlantic Ridge, revealing Earth's largest mountain range hidden underwater. This seismic finding triggered the theory of plate tectonics—explaining how continents drift. The ridge stretches for over 16,000 kilometers beneath the Atlantic Ocean. ✨
#discovery⚡#geology⚡#oceanography
👉subscribe Interesting Planet
👉more Channels