Функция 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
#Greenland🇬🇱
Eternal ice 🧊 Would you like to visit here?
About 80% of the territory of Greenland is covered with an ice shield, which is the second largest in the world after Antarctica. The ice in some places reaches a thickness of up to 3 km.
Greenland cuisine is based on the gifts of nature: fish, seafood, venison and dishes from marine mammals. For example, "Suasat" - sewen soup - is considered a traditional dish.
Отвлечемся на секунду от новостей автопрома и поговорим чуть о том, что в мире нет стабильности. Суматошный нестабильный эксцентричный президент США хочет заграбастать Гренландию.
В одном из своих интервью он сказал, что армия Гренландии состоит из двух собачьих упряжек. Гордые жители создали шедевральный ии-шный ролик (точно пару дней потратили) в котором продемонстрировали свои военные возможности. У них есть собаки, моржи и пингвины (почему-то в форме образца СССР).
Что мы вообще думаем об этой ситуации. Заберет или не заберет?
Заберет - 👎
Не заберет - 👍
Вообще это какая то дичь - 🥴
Ролик огонь - ❤️
#greenland
#GREENLAND RESULT
—————————
PEAK: 1,109%
If you think that was a great move, you haven't seen what we have planned for our next launch...
After giving it to you guys, we pushed #GREENLAND over 1,100% in a matter of less than an hour, destroying our target and guaranteeing the biggest profits for our members.
Trump is about to move the global economy again, and we're about to have the biggest 100x opportunity we've had in years. We're just getting started
Stay tuned.
👣 The iceberg's breath in northeast
Greenland. Silence and icy expanses where every breath feels like nature itself.
📏
📏
📏
📏
📏
📏
📏
📏
#Greenland | @voyage
👣 The iceberg's breath in northeast Greenland. Silence and icy expanses where every breath feels like nature itself.
📏
📏
📏
📏
📏
📏
📏
📏
#Greenland🇬🇱@voyage
#GREENLAND RESULT
—————————
PEAK: 1,109%
If you think that was a great move, you haven't seen what we have planned for our next launch...
After giving it to you guys, we pushed #GREENLAND over 1,100% destroying our target and guaranteeing the biggest profits for our members.
Trump is about to move the global economy again, and we're about to have the biggest 100x opportunity we've had in years. We're just getting started
Stay tuned.
👣 The iceberg's breath in northeast Greenland. Silence and icy expanses where every breath feels like nature itself.
📏
📏
📏
📏
📏
📏
📏
📏
#Greenland🇬🇱@voyage
The United States abandoned the idea of seizing Greenland due to the threat of impeachment to Trump, - Reuters
#Trump#Greenland
👂More on Trump's Ear ⚠️
The world would be a “better, more secure place” if America took over Greenland, Nigel Farage said at Davos, while insisting that he still believed in the sovereignty of nation states.
During a panel at the World Economic Forum’s “America House” in the Swiss ski resort on Wednesday, the Reform UK leader said he had “no doubt” that the world would be safer if a “strong America” was in Greenland “because of the geopolitics of the high north, because of the retreating ice caps and because of the continued expansionism of Russian icebreakers, of Chinese investmen
#Trump#Greenland
👂More on Trump's Ear ⚠️
The United States needs Greenland for national security reasons, Trump said.
According to the US president, the island is important for the creation of the Golden dome system. And NATO is supposed to pave the way for America to get Greenland.
#Trump#Greenland
👂More on Trump's Ear ⚠️