Функция 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
Every parent needs to listen to this life-changing tip from PM Modi! Let your children make their choices in life & make their own path
👉 To listen to more mantras of success, Don't forget to watch #PPC2023 on 27th Jan 2023
https://youtu.be/Fwdx_cBqiDU
Every parent needs to listen to this life-changing tip from PM Modi! Let your children make their choices in life & make their own path
👉 To listen to more mantras of success, Don't forget to watch #PPC2023 on 27th Jan 2023
https://youtu.be/Fwdx_cBqiDU
परीक्षा से पहले की तैयारियों को लेकर अब बिल्कुल न हो परेशान; क्योंकि प्यारे बच्चों जल्द आ रहा है प्रधानमंत्री के साथ परीक्षा पे चर्चा 2023 संवाद।
#PPC2023
https://youtu.be/SKmrRc2-QTQ
अपने पैशन को चुनें या एक अच्छे करियर की प्लानिंग करें?
करियर या परीक्षा से जुड़े आपके सभी सवालों के पीएम 27 जनवरी 2023 को देंगे जवाब। #PPC2023
https://youtu.be/RzB7PY4VX0w
विजिट करें: mygov.in/ppc-2023/
परीक्षा से डरने के बजाय मुस्कुराते हुए उसे अपना बनाएं।
27 जनवरी, 2023 को #PPC2023 में प्रधानमंत्री के टिप्स से परीक्षा या करियर से जुड़े आपके हर सवाल का मिलेगा समाधान।
#PPC2023
👆Wondering how to create a perfect balance of studies and sports for your children during exams? PM Modi is here to help
Participate in #PPC2023 and get tips on dealing with your children's exam stress!
Visit: innovateindia.mygov.in/ppc-2023/
👆Become the best coach, mentor and teacher of your children with the help of PM's tips and advice!
Participate in #PPC2023 and make your children exam ready
Visit: https://innovateindia.mygov.in/ppc-2023/
परीक्षा के मुश्किल दिनों को बनाएं खुशनुमा और तनावमुक्त। परीक्षा पे चर्चा 2023 में शामिल होने के लिए भेजें अपने सुझाव और सवाल, आपको मिल सकता है प्रधानमंत्री से सीधे संवाद का मौका।
#PPC2023
https://youtu.be/YcV_uea2ok8
👆Become the best coach, mentor and teacher of your children with the help of PM's tips and advice!
Participate in #PPC2023 and make your children exam ready
Visit: https://innovateindia.mygov.in/ppc-2023/
👆Help your children reach their maximum potential this exam season, with PM Modi's inspiring advice!
👉 Participate in #PPC2023 and make your children exam ready.
Visit: https://innovateindia.mygov.in/ppc-2023/
👆Become the best coach, mentor and teacher of your children with the help of PM's tips and advice!
Participate in #PPC2023 and make your children exam ready
Visit: https://innovateindia.mygov.in/ppc-2023/