Функция 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
#ComingSoon: An integrated development at Yew Tee which will house 2-room Flexi flats for seniors, a community club, a polyclinic, retail shops, and Choa Chu Kang’s first hawker centre all under one roof!
P.S. The 2-room Flexi flats will be launched in the upcoming November sales exercise, along with over 4,000 flats in Hougang, Jurong West, Kallang/Whampoa and Tengah 😊
(Photo credit: MKPL Architects)
🚨The SingSing Tycoon NFT Marketplace is on its way🚨
💥 Trade exclusive NFTs for profits.
💎 Flex your collection.
🎮 Unlock game-changing assets.
Get ready to take your SingSing Tycoon experience to the next level! 🚀
🔜 Your favorite NFTs, all in one place—stay tuned for more details 👀
#NFT#SingSingMarketplace#ComingSoon
🎤Announcement | Chat | X (Twitter) | Website | Game
🚀 Big News Alert 🚀
$SING is gearing up for an exciting CEX listing next week! 📈 But we’re keeping the exchange a secret…for now! 🤫
Guess the CEX & get ready for the reveal! 🔥
#SingSing#CEXListing#ComingSoon
🎤Announcement | Chat | X (Twitter) | Website | Game
Kaptaan | Official Teaser | Amazon MX Player
Language: Hindi
Genre: Drama, Crime, Thriller
jahan insaaf ki zarurat ho, wahan Kaptaan ki entry pakki hai ⚖️🔥
Kaptaan, coming soon, only on Amazon MX Player for FREE!
watch now🔗- https://youtu.be/X4Kb6K7B61o
#Kaptaan#AmazonMXPlayer#ComingSoon
Famously Fit with Sophie | Official Trailer | Amazon MX Player
Language: Hindi
Genre : Fitness based Chat Show
Bollywood fitness secrets, finally out 👀
Famously Fit with Sophie, coming soon only on Amazon MX Player for FREE!
watch now - https://youtu.be/Cs6lCuRgBC8
#AmazonMXPlayer#ComingSoon#FamouslyFitwithSophie
🔜 Exciting partnership announcement coming soon! 🎉
Can you guess who will be integrating SingSing's SocialFi SDK next? 🤔
Stay tuned for the big reveal! 🚀✨
#Partnership#SocialFi#SingSing#ComingSoon
📢CLOSED BETA WHITELIST CLOSED
Attention, QuasarK Community: the application period for our closed beta is now officially closed. We want to express our heartfelt thanks ❤️ to everyone who applied and showed their interest in being a part of this exclusive testing phase. Your support and enthusiasm mean the world to us! 👏
🚀 But hold on tight, because the journey is just getting started! In a matter of days we’ll be reaching out to our whitelisted beta testers🏆. If you made it to the whitelist, keep an eye on your notifications and direct messages 📩 as we will be sharing important updates and instructions with you. BEWARE OF SCAM!
Stay tuned for more updates and announcements 👀 as we continue to make progress towards the launch of QuasarK. We appreciate your ongoing support and look forward to embarking on this exciting journey together!
#QuasarK#ClosedBeta#BetaTesters#ComingSoon