Функция 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
#EGLD/USDT analysis :
#EGLD is currently in an uptrend, trading above the 200 EMA. The price has successfully broken out and retested the previous swing high resistance levels. It is anticipated that the price will bounce back from this point and continue its bullish momentum, aiming to test the recent swing high.
TF : 4h
Entry : $28.44
Target : $33.75
SL : $26.00
#EGLD/USDT analysis :
#EGLD has broken out and retested the support zone. It is now expected to bounce from this support zone and test the previous swing high level.
TF : 1D
Entry : $26.26
Target : $28.14
SL : $25.12
#EGLD Weekly Support Zone Retest🧐
MultiversX is testing the lowerboundary of the descendingchannel formation on the weekly timeframe👨💻
This area serves as a launchpad for a potential bullish reversal🔍
A confirmed rebound could propel the price toward targets at $7, $12, $22, $38, $58, $77, $120, and $200🎯
#EGLD
MultiversX has successfully broken out of the descendingchannel pattern on the daily timeframe
Price action shows strong bullish momentum after breaching the descending resistance
Expect a continuation toward targets at $20.50, $26.00, and $38.00🎯
#EGLD bounced back from the Green zone on 12H Time frame,we expect more pumps after breakup from the Trendline,send it 💎
❄️@signals_bitcoin_crypto❄️
❄️@Shadow_support0o❄️
#EGLD is trying to break up the Supply zone on Weekly time frame,in the case of breakout we may see another bullish leg🚀
❄️@signals_bitcoin_crypto❄️
❄️@Shadow_support0o❄️
💰#EGLD price bounced from the support of $30.50-$31 area. The local resistance is $32.89-$33.50 area and the price is rejected from there. 👀
The major resistance is the $37.10-$38 area. You can open long positions near the support area with tight stop loss.
📈
❄️@signals_bitcoin_crypto❄️
❄️@Shadow_support0o❄️