Функция 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
🚀 Back to Back profits are made in the Premium Group
🎯🎯#DUSK/USDT has covered all the target to give a Profit of 22% to all Premium Members
👁🗨Contact @futurechief to enter the Premium Futures & SPOT Group for daily gain
🚀🚀Raining Profits in the Premium Group
🎯🎯#DUSK/USDT has covered all the targets to give an amazing profit of 75% for all Premium Members
👁🗨Contact @futurechief to enter the premium group & make daily gains on Futures as well as Spot Market
🎯🎯Excellent 23% Profit on #DUSK/USDT for all Premium Members
🚀🚀It has crossed all the targets
👁🗨Contact @futurechief to enter the premium group & make daily gains
#DUSK/USDT analysis :
#Dusk is currently in a downtrend and making new lows. The price has broken below support and is anticipated to resume bearish momentum and test lower levels. Wait for a retest of the broken support for a short entry opportunity.
TF : 1D
Entry : $0.1062
Target : $0.0730
SL : $0.1280
#DUSK/USDT analysis :
#DUSK is currently attempting to break through the trendline and rise higher to test the previous swing high. The price has formed a double bottom pattern within the support zone, which further indicates the potential for upcoming bullish momentum. It is advisable to wait for the price to break the trendline before considering a long entry.
TF : 1D
Entry : $0.1910
Target : $0.2520
SL : $0.1508
😳#DUSK +60% за 3 дня!
Dusk — Layer-1 блокчейн с Zero-Knowledge proofs (ZK-SNARKs) для полной приватности транзакций и смарт-контрактов. Поддерживает конфиденциальную токенизацию реальных активов (RWA), DeFi и торговлю с встроенной регуляторной совместимостью (MiFID II, MiCA).
Токен доступен: MEXC
Crypto Headlines
#DUSK/USDT analysis :
#DUSK is currently consolidating within a channel. The broader trend on larger timeframes suggests a bearish outlook, indicating a possible breakout from the channel to further descend towards lower price levels. It is recommended to await a breakout from the channel and a drop below the $0.1932 level before considering entering a short position.
TF : 4H
Entry : $0.1932
Target : $0.1508
SL : $0.2195
🚀🚀 20% Profit on #DUSK/USDT for our Premium Members on Binance Futures/Bybit/OKXX/Kucoin/Bitget
✅✅ All target completed
👁🗨Contact @primemod to enter the Premium Group for high quality SPOT & FUTURES Signals
🚀🚀 525%+ Huge Profit on #DUSK/USDT as it has hit all the profit target with great easiness - The trade has been closed today
👁🗨Contact @primemod to enter the premium group & make daily gains
🚀🚀 590%+ Huge Profit on #DUSK/USDT as it has hit all the profit target with great easiness - The trade has been closed today
👁🗨Contact @primemod to enter the premium group & make daily gains