Функция 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
🌌Welcome to the Future of Crypto and AI: AskAnyGPT.com🌌
💎 Introducing AskAnyGPT, the ultimate fusion of cryptocurrency and artificial intelligence technologies. Our platform unlocks the potential of AI-driven content generation, chatbots, NFTs, and video creation – all while enhancing your crypto experience with #YieldFarming, Layer-1 & 2 compatibility, and seamless blockchain bridging. Experience the limitless creative possibilities at the forefront of the #AI and #Blockchain revolution.
🚀 AskAnyGPT is the undisputed leader in AI-powered blockchain solutions, offering a comprehensive suite of innovative products:
🔹 AskAnyGPT Chatbot
🔹 AI Image / NFT Generator
🔹 AI Code Translator
🔹 AI Video Generator
🔹 AI Discord & Telegram Bots
🔹 AI Yield Farm
🔹 AskAny GPT SDK
🔹 Mint NFT
🔹 Marketplace
🔹 BSC / Arbitrum / Ethereum Bridge
🔹 Layer-1 & 2 AI-Compatible Blockchains
🔹 DEX / CEX Listing Post-Launch
🔹 CMC / CGK Fast Listing
⚡️Official Launch: May 17th ⚡️
💰 Airdrop AskAnyGPT: 💰
🎁 Reward: $15,000 in $ASK token!
🏆 Winners: 1000+
🤑 Airdrop Link:Here! Secure your spot NOW.
🖥 Official Links:
Website | Daps | Whitepaper | Twitter | Discord | Telegram Chat | Telegram News | Medium
After the horse , what comes next?
yes , a Cow
New farm on #TAPSWAP OASIS pool, A single asset staking where you can stake $BIFI and earn $TAPS!
Check it out!✍️
https://dapp.tapswap.money/#/pools
#HotDeFiSummer#BSC#AMM#YieldFarming#ApeSwap
Watch the video, like it 👍 and comment 💬 to get a prize!
🎞youtube.com/XBANKING
🎞youtube.com/XBANKING
🎞youtube.com/XBANKING
💵 The author of the best comment will get $10 from our channel!
Don't forget to subscribe to our YouTube channel!
#DeFi#Crypto#PassiveIncome#YieldFarming#LiquidityPools#Web3#XBANKING#CryptoInvesting
🚀 Enhanced Labs Secures $1 Million in Pre-Seed Funding for DeFi Expansion
DeFi solutions provider Enhanced Labs has announced the successful completion of a $1 million pre-seed funding round. According to Odaily, the round was led by Maximum Frequency Ventures, with participation from GSR, Selini, Flowdesk, and a group of angel investors. The newly acquired funds are expected to support product development and operations, as well as expand options-based yield strategies to a broader range of on-chain assets, including tokenized real-world assets.
#DeFi#Funding#PreSeed#Crypto#Blockchain#YieldFarming#TokenizedAssets#Startup#Investment#CryptoNews
Bidask: $RAFF & $WEB3 Listings, MyTonWallet & DeWallet Integration + Meme Contest
🏴Two new tokens are now live on Bidask:
• $RAFF — from the Ton Raffles ecosystem
• $WEB3 — from the .ton domain ecosystem
Both are now tradable in pairs against #TON. The WEB3/TON pool features boosted farming through August 5, with up to ~44% APR — rewards in $WEB3 scale based on daily trading volume:
➖ $12.5/day if volume > $10,000
➖ $25/day if volume > $15,000
➖ $37.5/day if volume > $18,000
➖ $50/day if volume > $20,000
➖ $67.5/day if volume > $23,000
➖ $75/day if volume > $25,000
🏆Bidask Meme Contest
Create a meme about Bidask Protocol, post it on X (Twitter) with the hashtag #BidaskMemeContest, and share it in the contest thread in the “meme contest thread” in the Bidask chat.
Only memes posted in both X and the chat thread will qualify.
Contest runs through August 7. Prizes include:
🥇 1st — Toy Bear #52238
🥈 2nd — Record Player #10315
🥉 3rd — Crystal Ball #3932
🏅 4th — Light Sword #7136
🏅 5th — Light Sword #72658
👛 Wallet Integrations
#MyTonWallet and DeWallet (by DFC ecosystem) have added Bidask DEX support — making it even easier to swap and farm.
📈 Top APRs on Bidask DEX right now:
• HYDRA/TON — ~1250% APR
• TON/USDT — ~87% APR
Bidask DEX |Channel
#Bidask#WEB3#RAFF#DeFi#YieldFarming#CryptoNews#CryptoTrading#TON#TONBlockchain#DEX