Функция 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
#APE/USDT analysis :
#APE is currently demonstrating a bullish trend, characterized by higher highs and higher lows, with strong support along the trendline. The price has recently bounced back and successfully broken out of the trendline, suggesting a continuation of bullish momentum. It is anticipated that the price will test previous highs moving forward.
TF : 1D
Entry : $1.330
Target : $1.930
SL : $0.988
#APE/USDT analysis :
#APE is currently in an upward trend, consistently achieving new highs while trading above the 200-period exponential moving average (EMA). The price is currently consolidating above a support zone that has been tested multiple times. It is expected that the price will bounce off this level and continue its upward trajectory, with the potential to revisit previous highs.
TF : 30min
Entry : $1.890
Target : $2.160
SL : $1.760
#APE/USDT analysis :
#APE is currently in a downtrend, trading consistently below the 200 EMA. The price is currently within a resistance zone. It is anticipated to face rejection from this zone and continue its downward trajectory.
It is advisable to await the breakout of the $0.580 level for a short position, with the previous swing low likely to be tested.
TF : 30min
Entry : $0.580
Target : $0.537 and $0.509
SL : $0.607
📈Инсайдер «0x0b8a» превратил $174 000 в $2,45 млн (14x) всего за один день
Он открыл лонг по #APE прямо перед ростом цены и вышел почти на самом пике, зафиксировав $1,79 млн. Сразу после этого открыл шорт и заработал еще $488 000 – lookonchain.
🟪Чат▫️Новостной канал▫️Премиум сигналы
#APE
ApeCoin is completing a cup and handle formation on the daily chart🧐
Also, the price has breached above the descending resistancelevel and the MA 50
A move above the neckline could drive the price toward targets at $0.85, $1.00, $1.20, and $1.36🚀
#APE
ApeCoin is moving towards a key resistance level, showing potential for a significant move
A breakout from the descending channel could trigger a 100-120% bullish wave in the mid-term️