Функция 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
🎞 YOUTUBE KANAL OCHISH XIZMATI #PREMIUM
🇺🇿🇺🇸O'zbekcha va Amerikan kanal ochib beramiz!
✅ Kanal uchun yo'nalish tanlashda yordam beramiz
✅ Kanal uchun original nom o'ylab topamiz
✅ Kanal ochamiz va to‘liq sozlab chiqamiz
✅ Standart Banner va Avatarka ishlab beramiz
✅ Telefon raqam bilan tasdiqlab beramiz
🧑💻 1 OYLIK NAZORAT: 30 kun davomidaadmin — kanalingizni kuzatib, nazorat qiladi va savollaringizga javob beradi!
🎁 BONUS: “VIGETA PRIVATE” yopiq kanalimizga 1 oylik tekin a’zolik🎁
💰 Narx: 349 000 so‘m
⏰ Topshirish muddati: 2 kun
🛒Buyurtma berish:
✍️@Vigeta_Admin
✅ 300 dan ortiq kanallarni muvaffaqiyatga boshladik — navbat sizniki!
➖➖➖➖➖➖➖
😎VIGETA | BLOGERLAR UCHUN
#Premium💸
The world of crypto and particularly futures trading is a beautiful world. 💎
Detailing a profitable trade requires a great team. We provide all this for you with pay a small fee in a VIP channel.
Join us👉@shadow_crypto_bot
#Premium🔥🔥
The world of crypto and particularly futures trading is a beautiful world. 💎
Detailing a profitable trade requires a great team. We provide all this for you with pay a small fee in a VIP channel.
Join us👉@shadow_crypto_bot
#Premium🔥🔥
The world of crypto and particularly futures trading is a beautiful world. 💎
Detailing a profitable trade requires a great team. We provide all this for you with pay a small fee in a VIP channel.
Join us👉@shadow_crypto_bot
#Premium🔥
The world of crypto and particularly futures trading is a beautiful world. 💎
Detailing a profitable trade requires a great team. We provide all this for you with pay a small fee in a VIP channel.
Join us👉@shadow_crypto_bot
#Premium💰
STOP losing money trading alone
STOP telling yourself every time that you will make it back, but every time you lose it all.
STOP letting opportunities pass you by.
💯One of our signals is always more than 100%, which means x2 to the deposit.
💎join us to enjoy our signals💎
#Premium
The world of crypto and particularly futures trading is a beautiful world. 💎
Every day, absolutely every day, there are huge opportunities to make money.💸
Join our community now to take advantage of our exceptional signals and to finally be able to make a lot of money with crypto. 🤑
🌟join us to enjoy our signals🌟
Bot Dukungan Resmi Smart Glocal
Beberapa waktu lalu, pengguna menemukan bot @tgpb_support_bot, yang memiliki tanda centang verifikasi resmi dan dirancang untuk menangani pertanyaan terkait pembayaran langganan Telegram Premium yang dilakukan melalui @premiumbot.
Bot ini dapat berguna bagi pengguna yang telah membayar langganan melalui @premiumbot tetapi belum melihatnya muncul di akun mereka.
#premium