Функция 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
🌍 The lithosphere, atmosphere, hydrosphere, and biosphere constantly exchange matter—volcanic eruptions can shoot minerals into the air that later fall into oceans, nourishing marine life far away. ✨
#lithosphere⚡#atmosphere⚡#hydrosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 When huge dust storms sweep across deserts, fine particles from the lithosphere reach the atmosphere, circle the globe, and even fertilize distant rainforests—linking Earth’s spheres in invisible ways. ✨
#lithosphere⚡#atmosphere⚡#hydrosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 A single major volcanic eruption links all of Earth’s spheres—rock and magma from the lithosphere, gas and ash in the atmosphere, water vapor in the hydrosphere, and rapid changes in the biosphere. ✨
#lithosphere⚡#atmosphere⚡#hydrosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The hydrosphere holds less than 0.01% of Earth's water in rivers and lakes, while most is locked in glaciers, ice caps, or underground. These hidden reserves link all of Earth’s spheres. ✨
#hydrosphere⚡#lithosphere⚡#biosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The deepest part of the ocean, the Mariana Trench, reaches nearly 11,000 meters below sea level. Here, the hydrosphere, lithosphere, and biosphere all meet in extreme conditions. ✨
#hydrosphere⚡#lithosphere⚡#biosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The deepest point on land, the Dead Sea Depression, lies about 430 meters below sea level, linking the lithosphere, atmosphere, hydrosphere, and biosphere in an extreme environment for life. ✨
#lithosphere⚡#hydrosphere⚡#biosphere⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 At the bottom of Antarctica’s ice lies a vast liquid lake called Lake Vostok, sealed under 4 kilometers of ice. This hidden hydrosphere supports unique life forms adapted to total darkness. ✨
#hydrosphere⚡#Antarctica⚡#secrets⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍