Функция 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
Latest offers:
Máster en Comercio Electrónico con WordPress 2026 by Renato Jesús Yacolca Neyra
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse
Latest offers:
Master Course : Making the Business Case for Sustainability by Dr. José Prabhu J
👉Go To The Course
-----------
Teaching Methods, Teaching Quality & Teaching Delivery 3.0 by Dr. José Prabhu J
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse
Latest offers:
Professional Diploma in Project Management by Md. Aliful Islam
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse
Latest offers:
Master Course in Smart Cities, Urban Planning & Development by Dr. José Prabhu J
👉Go To The Course
-----------
Master Course in Corporate Social Responsibility (CSR) by Dr. José Prabhu J
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse
Latest offers:
Master Course in Project Management 2.0 by Dr. José Prabhu J
👉Go To The Course
-----------
Multigenerational Leadership & Reskilling Your Organization by Dr. José Prabhu J
👉Go To The Course
-----------
Master Course in Climate Change Impact on Business by Dr. José Prabhu J
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse
Latest offers:
NumPy, SciPy, Matplotlib & Pandas A-Z: Machine Learning by Sara Academy
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse
Latest offers:
Certificado Profissional em Liderança e Gestão by MTF Institute of Management, Technology and Finance
👉Go To The Course
-----------
Curso Completo de Mikrotik. Configuraciones y mucha Práctica by Alvaro Chirou , Kevin Lopez , Walter Coto , Ciberseguridad Hacking Seguridad Informática
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse
Latest offers:
Programador Java en 37 Días Con práctica de Entrevista y más by Alvaro Chirou , Walter Coto , Kevin Lopez , Programación | Desarrollador Full Stack | FrontEnd | BackEnd | BD
👉Go To The Course
-----------
The Complete JavaScript Course: From Zero to Expert by Sara Academy
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse
Latest offers:
Language Learning with AI: Practical Skills Guide by Andrii Piatakha
👉Go To The Course
-----------
AI for Customer Success: Transforming Customer Relationships by Andrii Piatakha
👉Go To The Course
-----------
AI for Business Analysts by Agile Enterprise Coach London
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse
Latest offers:
Carbon Capture (CCUS): Governance, Policy, & Social License by Alex Chyzh
👉Go To The Course
-----------
Mastering Manus: AI Automation for Marketing & Content by Anton Voroniuk , Anton Voroniuk Support
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse
Latest offers:
Innovative AI Practices in Telemedicine & Virtual Care by Starweaver Team , Paul Siegel , Renate Zara
👉Go To The Course
-----------
Emotional Intelligence in Teams and Collaboration ( EQ ) by Starweaver Team , Paul Siegel , Eric Zackrison
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse