Функция 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
Join us in 20 minutes to explore the meme ecosystem on #BSC with @LordCheems_Bsc & @Testonbsc! 👀
⏰ 1PM UTC+0
📅 Tuesday, February 11th
📍https://x.com/i/spaces/1BdGYqlaOeXGX
🔜 Tune in to our BNB AMA today to learn about #BSC Governance and discover how you can get involved!
⏰ 1PM UTC
📅 Today, October 24th
📍 BNB Chain X, YouTube, & Binance Live
🔗https://youtube.com/watch?v=vmS1TPNKt4s&ab_channel=BNBChain%28Official%29
🚨 The final sunset of BNB Beacon Chain is set for mid-November!
Migrate your assets to #BSC to avoid losses.
Learn about the asset migration process and necessary actions for users and CEXes on the blog below! 👇
https://www.bnbchain.org/en/blog/final-sunset-plan-of-bnb-beacon-chain
🔥🔥🔥LIVE ON 8 SEPTEMBER (9PM GMT+3) 🔥🔥🔥
TIPSY Token #BSC on 🥞PancakeSwap!!!
The First Blockchain-based Adult-Friendly Entertainment Ecosystem.
Tipsy is an app store - and a place where adults have fun!
It's an open-source marketplace for adult entertainment.
It's a platform where developers can create and deploy apps and games, merchants can sell goods and models can upload and share media or offer services such as video chat.
Tipsy is an ecosystem - with interoperability between apps and games
✅Certik Audited
✅Low MC
✅Very Low Circulating Supply
✅Vesting(Double your Tokens)
✅NFT
🚀 CEX Listing
🔗 Virtual Land Sale
❤️ TipsyFans
🌎 TipsyWorld
📞 Telegram: https://t.me/tipsyonline
🌐 Website: tipsyonline.io
🐦 Twitter: twitter.com/TipsyLabs
🎥 YouTube: https://youtu.be/-uBU3s5uSPk
👋
✅ WELLCOME TO ✅
💯$HGT
✅ PRE-SALE COMING
🚨$HGT — backed by more than hype. It’s backed by gold.
👉 From the producing Hellyer Mine in Tasmania 🇦🇺, $HGT gives you exposure to tokenized gold, lead & zinc — all secured by audited reserves.
🌱 Built on #BSC, powered by hydroelectric energy
🔒 Audited reserves. Institutional custody.
🟢 Gold-backed stablecoin launching in Phase2
🔥 Pre-sale COMING — limited allocation, real utility
🕊Twitter
https://x.com/Hellyergold
🔵Telegram
https://t.me/HGTToken
🌐Website
https://hellyertoken.co/
🚀 New Gem 💎 : Daddy Cake
💲 Total Supply: 1,000,000,000,000,000
⏱ End date : Aug 15th, 2021
⏳ Distribution Date : Sep 1st, 2021
🔘 Rate : ⭐️⭐️⭐️⭐️⭐️
🏚 Aidrop :
🔸 Fill in the form with your details:
https://forms.gle/uzEC2Kp33xiySegp7
🔸 Join the Telegram group:
@DaddyCake_Chat
🔸 Join the Telegram channel :
@daddycakechannel
🔸 Buy:
https://pancakeswap.finance/swap?outputCurrency=0x98899de44fdfe52b385fbe53c82042bbbcb8e673
🔸 Follow the Twitter account:
https://twitter.com/daddycake_bsc?s=21
🔸 Retweet our pinned post on your Twitter account & tag 5 friends.
📑Additional Information:
DaddyCake.io - Meme that’s Hyper deflationary with built in smart staking system, hold, pet, love, & save dogs! on #BSC
Contract:
0x98899de44fdfe52b385fbe53c82042bbbcb8e673