Функция 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
🤑Gate.io Startup Answer & Earn @walken_io💵
📝Take the quiz about Walken(WLKN) & Split a $3,000 mega prize!🏆
⏰Ends at 9:00AM, Jul 25th (UTC)
*How to participate:
✅ Join GateioOfficialNews and Walken community
✅Follow @Gateio_Startup & RT the 👉POST
🔛 Click 👉HERE to Participate now
Learn More:https://www.gate.io/startup
#Gateio#gateiostartup
📣Startup Voting Campaign #4 - $8,000 up for grabs
Vote for your favorite project by 6:00 AM, Sep 8 (UTC)!
🏆Winning projects will shine in the spotlight!
💎$BYIN$CEC$MAK$ANS
🔄Share to rally support for your pick!
👉Vote:https://gate.io/activities/startupvote?gt_disable_intercept_jump=1&now_period=5
#GateioStartup#Memecoins#Airdrop
📣Day 3 of voting! $8,000 up for grabs—vote for your favorite project by 6:00 AM, Sep 8 (UTC)!
🏆Winning projects will shine in the spotlight!
💎$BYIN$CEC$MAK$ANS
🔁Share to rally support for your pick!
👉Vote:https://gate.io/activities/startupvote?gt_disable_intercept_jump=1&now_period=5
#GateioStartup#Memecoins#Airdrop
🚀$8,000 up for grabs! #Vote for your favorite project by 06:00 AM, Sep 8 (UTC)!
$BYIN$CEC$MAK$ANS
🏆Winning projects get the spotlight
🔁Retweet to support your pick
Vote now:https://gate.io/activities/startupvote?gt_disable_intercept_jump=1&now_period=5
#GateioStartup#Memecoins#Airdrop
📈#Gateiopartner carnival: the main prize of $12,000 is being played out 🔥
The promotion is active until 11:00 Moscow time on February 24
ℹ️How to earn:
1) Registration on Gate + KYC2
2) Go here and click "Join now"
3) We complete the tasks:
🎁BONUS 1 : Registration + KYC, PrizeStartup voucher for 20 shares
🎁BONUS 2 : Make a deposit of $50, prize from $5 to $10
🎁BONUS 3 : Make a trading volume of $200, split the prize pool of $10,000 depending on the share in the total trading volume
🎁BONUS 4 : Invite users and share the prize pool of $2000
🔗Join now and earn: https://gate.io/fr/campaigns/396?ref=VLJMULHBVA
#Gateio#GateioStartup#Crypto
🚀Gate.io Startup Free Offering: Cat Gold Miner (CATGOLD)
🗓Subscription Period:06:00AM January 7 - January 9 (UTC)
💵Airdrop Amount: $50,000 CATGOLD
👉Sign up here
🔗
⏰Trading Starts:10:00,AM January 9 (UTC)
📚Full Details:Click here
🎉Gate.io New Year Red Envelope: Get a $60 bonus by following this link ➜ Red Envelope
⚡️Don’t miss this unique chance to accelerate your earnings with CATGOLD! Places are limited, register now and be among the first to take advantage of this exclusive offer! ⭐️
🔗gate.io
📈
#GateioStartup#Gateio#CATGOLD
💰Trade $HQ on Gate.io & Win Your Share of $4,000!
👀 A new trading event is live on Gate.io, giving you the chance to earn big rewards!
🗓Event Period: February 7 at 06:00 AM UTC - February 12 at 06:00 AM UTC
💰Rewards:
✅$3,000 Trading Bonus – Trade at least $50 in HQ and share a $3,000 prize pool.
✅$950 New User Bonus – New users who sign up and trade $10 in HQ will receive $10 instantly.
✅$50 Lucky Reward – 1 lucky participant from the comments will win $50!
⚠️Important:
✔️ Complete your identity verification before the event ends to qualify.
✔️ Rewards will be distributed in HQ within 14 working days.
✔️ No multiple accounts or fraudulent activity allowed.
🔥Join now and start trading! Don’t miss your chance to win big!
🔗Sign up & start trading here: https://www.gate.io/signup/?ref_type=103
#Gateio#GateioStartup#StartupMining#Launchpool#Launchpad