Функция 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
❌🟠 Los Giants no anticipan hacer un contrato de nueve cifras para Tatsuya Imai ni para ningún otro lanzador en el mercado esta temporada baja, según Andrew Baggarly.
#️⃣#Giants
🗞 | t.me/MLB_Daily
🏥🌉 Los Giants están colocando a Logan Webb en la lista de lesionados con bursitis en la rodilla derecha, según Alex Pavlovic de NBC Sports Bay Area.
Es la primera vez que Webb está en la lista de lesionados desde 2021.
#Giants#LWebb
🗞 | t.me/MLB_Daily
🟠🤠 Según varios informes, incluidos los de Mark Feinsand de MLB.com, los Giants y el lanzador derecho Tyler Mahle han acordado un contrato de un año.
#️⃣#Giants#Mahle
🗞 | t.me/MLB_Daily
🟠 Según Ken Rosenthal, se informa que los San Francisco Giants están cerca de contratar a Tony Vitello, entrenador principal de Tennessee, como su nuevo manager.
#️⃣#Giants#Vitello
🗞 | t.me/MLB_Daily
🌎 The coconut crab is the world’s largest land-dwelling arthropod, able to crack open coconuts with its powerful pincers. These giant crabs live on islands across the Indo-Pacific, and their climbing and shell-breaking skills help them access food that other animals can’t reach. ✨
#animal⚡#giants⚡#adaptation⚡#islands
👉subscribe Interesting Planet
🪐 Unlike Earth and Mars, giant planets like Jupiter and Saturn do not have solid surfaces—their thick outer layers are made mostly of hydrogen and helium gas, which gradually becomes denser toward the center. These gas giants can have dozens of moons and faint ring systems, and their powerful magnetic fields—especially Jupiter’s, which is the strongest of any planet in our solar system—can trap charged particles, creating intense radiation belts that glow in radio waves. ✨
#Jupiter⚡#Saturn⚡#giants⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Jupiter, the largest planet in our solar system, is so massive that it has over twice the combined mass of all the other planets put together. Its rapid rotation—completing one spin every 10 hours—causes it to bulge noticeably at the equator, creating a distinct flattened shape unlike the more spherical profiles of smaller planets. ✨
#Jupiter⚡#giants⚡#rotation⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Saturn’s rings are made mostly of icy particles ranging from the size of grains of sand to mountains, but what’s remarkable is that these rings are incredibly thin—often only about 10 meters thick compared to their width of up to 282,000 kilometers. Despite their vast size, the rings would still fit comfortably within the gap between Earth and the top of our atmosphere if laid flat. ✨
#Saturn⚡#rings⚡#giants⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels