Функция 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
‘Sharing is off the table’ as #drought reshapes the lives of #Ethiopia’s pastoralists
Pastoralists in Ethiopia’s #Somali region say that worsening drought is eroding traditional systems of sharing that once helped communities survive.
Historically, Somali pastoralists survived drought through strong social networks. These Indigenous climate adaptations were built on an intricate system of mutual aid.
One of the most important systems is known as Gergar, a form of social insurance in which families who lose livestock receive animals from relatives and neighbors to help rebuild their herds.
“When people used to lose livestock, others would help them,” says Mohamed Abdi, a lifelong pastoralism advocate and director at Jijiga University’s Institute of Pastoral and Agro-Pastoral Development Studies. “We would move to relatives or sub clan areas, and they shared water and pasture with us.”
https://news.mongabay.com/2026/04/sharing-is-off-the-table-as-drought-reshapes-the-lives-of-ethiopias-pastoralists/
'Our children are next' fear #Kenyans as #drought wipes out livestock
In drought-hit northeastern Kenya, villagers have been forced to drag their dead livestock to distant fields for burning to keep the stench of death and scavenging hyenas away from their homes.
Mandera county along Kenya's borders with Ethiopia and Somalia has seen no rain since May and is now on the point of a full-blown water emergency.
"I have lost all my cows and goats, and burned them here," Bishar Maalim Mohammed, 60, a resident of Tawakal village, told AFP.
In his village, where most are pastoralists relying heavily on their animals, the only remaining bull can no longer stand. He has lain in the same spot for nearly a week, severely dehydrated with bones protruding through his skin, as his owner watches helplessly.
https://addisstandard.com/?p=55089
🌎 The Madagascan baobab, sometimes called the “upside-down tree,” stores thousands of liters of water in its massive trunk, allowing survival through severe drought. This clever reservoir keeps it lush while nearby plants wilt. ✨
#Madagascar⚡#baobab⚡#drought
👉subscribe Interesting Planet
Northern Kenya drought pushes millions to hunger
The lack of rain in northern Kenya means 2.4 million people in the region will struggle to find enough to eat by November, the United Nations World Food Programme says.
#News#Reuters#Kenya#drought#food#environment
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
U.N. warns of Madagascar 'climate change famine'
Madagascar produces less than 0.01% of global carbon dioxide emissions, but amid a fourth year of drought in the Grand Sud region, the U.N. is warning of a 'climate change famine'.
#Madagascar#UN#UnitedNations#ClimateChange#ClimateChangeFamine#GrandSudRegion#Drought#News#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖