Функция 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
🎄✨ Celebrate the joy of the season with Loot Baba [Official]!🎉
Wishing you a magical Merry Christmas 2025🎅 and a prosperous New Year ahead! ⭐️💎
Let’s welcome the future with endless opportunities and happiness! 🎁🔥
#merrychristmas@LootBaba_Officiall
Wishing all Nigerians a healthy and joyful Christmas! 🎄
May the spirit of the season bring happiness and well-being to your homes.
Stay safe, cherish moments, and embrace the gift of good health.
#MerryChristmas!🎄🎄
🇮🇩 Public Holidays in Bali
🎅 December 25 and 26 are official public holidays across Indonesia.
On these days, government institutions will be closed (including banks, tax offices, municipal offices, and other public services).
#MerryChristmas@BaliNews
¡Ay papá! Se acerca el #24Dic y lo que viene es rumba. Salí con Cilita a dar un recorrido por las calles de Caracas, vimos las fiestas navideñas; nuestro Pueblo está ejerciendo el derecho más bonito que tiene: el de la felicidad, vivir en Paz y disfrutar de este tiempo de unión. “¡No War!” #MerryChristmas
«Эта ночь принадлежит кроткому, посему пусть каждый отложит ярость и суровость, – принадлежит смиренному, пусть каждый обуздает свою гордость и смирит свое высокомерие. Ныне воссиял день милости, да не преследует же никто мщением нанесенной ему обиды; настал день радости, да не будет же никто виною печали и скорби для другого». (Ефрем Сирин. Слово на Рождество Христово). #καλαχριστουγεννα#merrychristmas
🎄✨ Merry Christmas from SingSing! 🎄✨
As the year comes to a close, we want to take a moment to express our heartfelt gratitude to our incredible SingSing community. 💖 Your unwavering support, enthusiasm, and passion have been the driving force behind everything we’ve accomplished together this year.
From building a thriving ecosystem to launching exciting games and features, none of this would have been possible without YOU. 🌟
🎁 This holiday season, we wish you and your loved ones endless joy, peace, and togetherness. May your days be filled with laughter, love, and the magic of Christmas. 🎅
Here’s to an even brighter and more exciting year ahead! Together, we’ll continue to grow, achieve, and make SingSing the #1 platform for all. 🚀
With love and gratitude,
The SingSing Team 💎
#SingSing#MerryChristmas#HappyHolidays
🎅Дорогие подписчики Легкого Неба!
🎉От лица руководства канала мы поздравляем вас с 2026 годом, желаем вам счастья, здоровья и главное - чистого и Лёгкого неба над головой!
🎅Надеемся, совсем скоро дед Мороз прилетит по Лёгкому небу к вам!
❄️Happy New Year!
Команда Легкое Небо
#merrychristmas#newyear#happy