Функция 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
Vladimir Vladimirovich Putin congratulated all Russian women on March 8th🌷.
"Dear women, you truly have everything within your power. You know how to create and build, combine strength and tenderness, and your desire to create a better future for your children inspires all of us to move forward,” the president emphasized.
Source: rt_russian
#holidays
🟠RCR | Support | Boost
Happy May 1st, Russian learners! ☀️
In Russia, we say:
• Мир! Труд! Май!
Peace! Labour! May!
But for you, let's change it a little:
• Май! Учёба! Русский!
May! Studying! Russian!
No work today. Just spring, rest, and one small verb conjugation. Maybe two. No pressure.
С праздником! ✨
Natalie with 🤍💙❤️
#holidays
🟠RCR | Support | Boost
🥳Today we celebrate:
• День женской дружбы
International Women's Friendship Day
Don't forget to congratulate your female friends!💋
#holidays
🟠RCR | Support | Boost
🥳Today we celebrate:
• День запрета на уныние!
No Moping Day! Cheerfulness Only Day!
🖼In the Russian Orthodox Church, moping or despondency is considered a major sin.
• Унывать (imperf.)
[oo-ny-vat']
Тo mope, to be despondent, to lose heart
Let's remember today's mantra! And NO moping! 💪
#holidays
🟠RCR | Support | Boost
Vladimir Vladimirovich Putin congratulated all Russian women on March 8th🌷.
"Dear women, you truly have everything within your power. You know how to create and build, combine strength and tenderness, and your desire to create a better future for your children inspires all of us to move forward,” the president emphasized.
Source: rt_russian
#holidays
🟠RCR | Support | Boost
Happy Wide Maslenitsa!
🔻Today marks the start of Широкая Масленица (Wide Maslenitsa) — the final and most festive part of this beloved Slavic holiday!
🔻Forget your diets this week. It's time for:
🥞 Endless piles of blini (pancakes)
☀️ Welcoming the spring sun
🔥 Burning the winter effigy
🥂 Being with family and friends
The Maslenitsa spirit in three words: eat, laugh, repeat!
🔻Whether you're enjoying blini with caviar, sour cream, jam, or just melted butter — may your week be delicious and your spring be bright!
С праздником!
RCRussian with 💓
#holidays
🥳Today we celebrate:
• День ответов на вопросы вашей кошки
Answer Your Cat's Questions Day
🔻On this important day, humans attempt to decipher what's really on their feline friend's mind, all in the pursuit of a better life for their whiskered overlord.
😉For example, your cat might be wondering:
👍Почему кормишь одной и той же едой?
Why do you feed me the same food every day?
🔸Почему не выпускаешь на улицу?
Why don't you allow me into the street?
🔸Почему нельзя драть диван?
Why is it not allowed to scratch the sofa?
🔸Где мои бубенчики?
Where are my balls/bells?
❗️What burning questions do you think your fluffy companion would ask you in Russian?
#holidays
🟠RCR | Support | Boost
🥳Today we celebrate:
• Международный День 'Спасибо'
International Thank You Day!
A simple word can mean everything.❤️
🔻Спасибо!
#holidays
🟠RCR | Support | Boost
Это всё мандарины!
It's all because of the tangerines!
🥳Today we celebrate:
• Международный Разгрузочный День
International Fasting Day
Ну вы поняли:)
🖼It's common for Russian to use 'e' instead of 'ё', as it often is clear for us what is meant.
#holidays
🟠RCR | Support | Boost