Функция 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
🎓✨ CONGRATULATIONS! ✨🎓
To all Jimma University students who passed the exit exam and will graduate this Saturday! 🌟
Your hard work and determination have led to this proud moment. Wishing you a future full of success, peace, and new beginnings! 🌍🎉
#JIFAR CAREER
Eid Mubarak! ✨ May this special day bring you joy, peace, and countless blessings. Wishing you and your loved ones happiness, prosperity, and togetherness. Enjoy the festivities and spread kindness! 🌙💙
#JIFAR CARRER
For those of you who find creativity challenging, try this
✨ Team up with someone who has similar goals or works on related projects.
Their ideas and experiences might open new doors and inspire fresh solutions.
Collaboration can increase your creativity and lead to amazing results—give it a try! 👊
#JIFAR TUTOR
@JifarSupport
Honoring and Memorizing this photo☺️😊
## JIFAR TUTOR:Unleash Your Potential, Embrace the JImma Aba Jfar Legacy
JIFAR TUTOR:Where History Inspires Your Future
> At JIFAR TUTOR, we're dedicated to bringing history to life, inspiring students to unlock their own potential and shape their own futures.
> Our Legacy
> * Student Spotlight Series: Hear from real students who are finding their own voices and shaping their own destinies, inspired by JImma Aba Jfar's example.
> * "Beyond the Textbook" Experiences: Explore local historical sites, connect with experts, and delve deeper into JImma Aba Jfar's legacy through real-world experiences.
> With JIFAR TUTOR, you'll:
> * Develop essential skills for success in the 21st century: critical thinking, communication, and problem-solving.
> * Discover your own leadership potential and find inspiration for creating positive change.
📝Visit Our channels: @JIFAR1
🛎Call 24/7':@JifarSupport 0953484398
#JIFAR TUTOR
#JIFAR TUTOR
New Job opening‼️
🎆We are Jifar Tutor🎆
✍️Place: Tshire
✍️Student: Grade 11
✍️Duration: 4 or 3 in a week
✍️Salary: monthly by Agreement
✍️#Females apply for this job
✍️ Subject All
📖We need punctual and who have excellent professional ethics and applicants for this position.
#Jifar HomeTutor #ጅፋር#ቤትለቤት(Online) #አስጠኚ
#በፈለጉን#ሁሉ#አለን! #
#የልጅዎ#እና#የርስዎ#ቀዳሚ#አጋር!
በዚህ ያናግሩን @JifarSupport
🎆 Jifar Tutor your choice🎆
ከታች ያለዉን የቴሌግራም ቻናላችን ይቀላቀሉ
👉@Jifar1
✅Job status - CLOSED‼️