Функция 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
Наш член Compliance Hub - Рустам Ахметов в рамках образовательной сессии C5+1 Youth Council и American University of Central Asia поделиться с молодыми экспертами полезной информацией по теме "Finances for Youth".
#compliance#awareness
#GreenSchool
#awareness
Ismoiljon Qosimov, one of the active members of the “Green School” Council of the Fergana region under the Ecological Public Association, organized an awareness event in the meeting hall of the Youth Affairs Agency.
During the event, special attention was paid to improving environmental culture, protecting the environment, and widely promoting “green” initiatives among young people. Participants were provided with detailed information about environmental issues, their solutions, and the responsibility of every individual in this regard.
Around 50 participants actively took part in the meeting, sharing their opinions and suggestions on the topic.
☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot
Instagram | Facebook | Twitter | Sayt | Youtube.
Stigma-fighting breast cancer van hits Gaza streets
Health activists have launched a campaign to raise awareness and fight the stigma associated with breast cancer in Gaza.
#News#Reuters#Gaza#breastcancer#awareness
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➖
Albinism: a genetic condition that reduces or stops the body's melanin production, the pigment that gives color to skin, hair, & eyes. Albino people often have very light skin, hair, and eye color. It can also affect vision, causing problems like poor sight and light sensitivity.
Most people with albinism have blue, hazel, green, or light brown eyes, depending on the amount of melanin pigmentation. Some may appear to have red or violet eyes since the lack of melanin allows underlying blood vessels to show.
Their skin is more sensitive to the sun, they burn easily and have a higher risk of skin damage. Albinism is present from birth and is inherited through genes. Most have normal health and lifespan with proper care. But many face social challenges like persecution, stigma, and discrimination in different parts of the world.
🧬☀️👁️
[Read more1]
[Read more2]
[Read more3]
[Read more4]
@googlefactss
#Albinism#Genetics#Awareness#Inclusion
If you have ideas or feedback contact us:
@Googlefactss_Feedback_bot
🇺🇸🇮🇱🇵🇸Lara Friedman on the #Antisemitism#Awareness#Act that is currently being passed, which will enshrine the #IHRA definition and examples into law.
"This is an effort to define antisemitism to not only include criticism of #Israel, but to use this as a weapon against #Palestinian rights activism".
@MostMoralArmy
Adults in some countries like for example Belgium and the Netherlands are in organ donor registers. Many do not actively choose, so they are listed as “no objection.” Around half are donors. Some actively say yes, some say no. Young adults often take no active choice and are donors by default.
Fun fact, there is no age limit for organ donation.
The oldest donor was 95 years old.
🫀📝🌍
[Read more 1]
[Read more 2]
[Related poll]
@googlefactss
#OrganDonation#Health#DonorRegister#MedicalFacts#Awareness#YouthHealth