Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Task Scheduling and Awaiting Results | Working with Asyncio Tasks
Python Asyncio Basics

bookTask Scheduling and Awaiting Results

When working with multiple asynchronous operations, you often need to run several coroutines at the same time and collect their results once all are finished. The asyncio.gather function is designed for this purpose. It takes multiple coroutine objects and schedules them to run concurrently. When you await the result of asyncio.gather, it waits for all the coroutines to complete and returns their results as a list, in the same order as the coroutines were provided. This makes it easy to manage and use the results of several asynchronous tasks together.

12345678910111213141516
import asyncio async def fetch_data(n): await asyncio.sleep(n) return f"Data {n}" async def main(): results = await asyncio.gather( fetch_data(1), fetch_data(2), fetch_data(3) ) for result in results: print(result) await main()
copy
question mark

Which statement best describes what happens when you use asyncio.gather to run several coroutines?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 2

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

bookTask Scheduling and Awaiting Results

Deslize para mostrar o menu

When working with multiple asynchronous operations, you often need to run several coroutines at the same time and collect their results once all are finished. The asyncio.gather function is designed for this purpose. It takes multiple coroutine objects and schedules them to run concurrently. When you await the result of asyncio.gather, it waits for all the coroutines to complete and returns their results as a list, in the same order as the coroutines were provided. This makes it easy to manage and use the results of several asynchronous tasks together.

12345678910111213141516
import asyncio async def fetch_data(n): await asyncio.sleep(n) return f"Data {n}" async def main(): results = await asyncio.gather( fetch_data(1), fetch_data(2), fetch_data(3) ) for result in results: print(result) await main()
copy
question mark

Which statement best describes what happens when you use asyncio.gather to run several coroutines?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 2
some-alt