Функция 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
🎉 Hey Crypto Enthusiasts! 🚀 Get ready for the launch of an exciting new token – OneBit (OBIT)! 🌟
🪙 Token Name: OneBit
💹 Symbol: OBIT
🎁 Don't miss our incredible Airdrop:
👥 1 USER = 200 OBIT Free!
🚀 PreSale Blast-off:
👉 1 USER = 10,000 OBIT + 0.05 BNB
🌐 Unlock more rewards with our referral program:
🔗 Referal Airdrop: +25% OBIT
🔗 Referal PreSale: Grab an extra 25% OBIT
📌 Secure your Airdrop on our official website: onebit.store/airdrop/index.html
📌Official Project Chat https://t.me/OneBit_Chat
Join us on this thrilling crypto journey with OneBit! 🚀✨ Don't miss out on this opportunity to be part of the future of finance! 🌐💰#OneBit#OBIT#CryptoRevolution🚀🌟
‼️ Please remember: We are airdrop hunters and only participate in free airdrops, please do not buy any airdrop token
We are thrilled to unveil our revamped pre-sale page, promising a lightning-fast and more animated experience! 🌐✨ But wait, there's more – we're introducing a game-changing feature to supercharge our token value: the Automatic Token Burn function! 🔥
In every pre-sale, when you make a purchase without referrals using any amount of BNB, that exact amount will be automatically burned from the total supply. 🔄 This strategic move is crafted to reinforce our token's value, aiming to maintain 1 OBIT = $0.01. 📈💰
Join us on this exhilarating journey toward a stronger and more vibrant community! 🌟💪
🔗 Website: onebit.store
💸 Airdrop: onebit.store/airdrop/index.html
🚨 New Update: Purchase 10,000 OBIT for only 0.05 BNB – offer is limited!
Plus, if you join without a referral, 25% of the purchased amount is burned from the total supply each time. 🔄
#CryptoNews#TokenBurn#PresaleMagic#OBIT#ToTheMoon🚀🌕
🌈 Embark on this journey with us and let's make history together! 🚀🚀🚀
https://www.youtube.com/shorts/S4iu3jA6Kac
🚀 Exciting News! 🚀
Dear Friends, we have revamped our pre-sale page for a lightning-fast and more animated experience! 🌐✨
But that's not all – we've introduced a game-changing feature to boost our token value: the Automatic Token Burn function! 🔥
Now, in every pre-sale, if you make a purchase without referrals using any amount of BNB, that exact amount will be automatically burned from the total supply. 🔄 This strategic move is designed to fortify our token's value and aims to keep 1 OBIT = $0.01. 📈💰
Join us in this exciting journey towards a stronger and more vibrant community! 🌟💪
Website: https://onebit.store/
Airdrop: https://onebit.store/airdrop/index.html
#CryptoNews#TokenBurn#PresaleMagic#OBIT#ToTheMoon🚀
We are thrilled to unveil our revamped pre-sale page, promising a lightning-fast and more animated experience! 🌐✨ But wait, there's more – we're introducing a game-changing feature to supercharge our token value: the Automatic Token Burn function! 🔥
In every pre-sale, when you make a purchase without referrals using any amount of BNB, that exact amount will be automatically burned from the total supply. 🔄 This strategic move is crafted to reinforce our token's value, aiming to maintain 1 OBIT = $0.01. 📈💰
Join us on this exhilarating journey toward a stronger and more vibrant community! 🌟💪
🔗 Website: onebit.store
💸 Airdrop: onebit.store/airdrop/index.html
🚨 New Update: Purchase 10,000 OBIT for only 0.05 BNB – offer is limited!
Plus, if you join without a referral, 25% of the purchased amount is burned from the total supply each time. 🔄
#CryptoNews#TokenBurn#PresaleMagic#OBIT#ToTheMoon🚀🌕
🌈 Embark on this journey with us and let's make history together! 🚀🚀🚀
https://www.youtube.com/shorts/S4iu3jA6Kac
🚀 Exciting News! 🚀
Dear Friends, we have revamped our pre-sale page for a lightning-fast and more animated experience! 🌐✨
But that's not all – we've introduced a game-changing feature to boost our token value: the Automatic Token Burn function! 🔥
Now, in every pre-sale, if you make a purchase without referrals using any amount of BNB, that exact amount will be automatically burned from the total supply. 🔄 This strategic move is designed to fortify our token's value and aims to keep 1 OBIT = $0.01. 📈💰
Join us in this exciting journey towards a stronger and more vibrant community! 🌟💪
Website: https://onebit.store/
Airdrop: https://onebit.store/airdrop/index.html
#CryptoNews#TokenBurn#PresaleMagic#OBIT#ToTheMoon🚀
We are thrilled to unveil our revamped pre-sale page, promising a lightning-fast and more animated experience! 🌐✨ But wait, there's more – we're introducing a game-changing feature to supercharge our token value: the Automatic Token Burn function! 🔥
In every pre-sale, when you make a purchase without referrals using any amount of BNB, that exact amount will be automatically burned from the total supply. 🔄 This strategic move is crafted to reinforce our token's value, aiming to maintain 1 OBIT = $0.01. 📈💰
Join us on this exhilarating journey toward a stronger and more vibrant community! 🌟💪
🔗 Website: onebit.store
💸 Airdrop: onebit.store/airdrop/index.html
🚨 New Update: Purchase 10,000 OBIT for only 0.05 BNB – offer is limited!
Plus, if you join without a referral, 25% of the purchased amount is burned from the total supply each time. 🔄
#CryptoNews#TokenBurn#PresaleMagic#OBIT#ToTheMoon🚀🌕
🌈 Embark on this journey with us and let's make history together! 🚀🚀🚀
https://www.youtube.com/shorts/S4iu3jA6Kac