done, pending = await asyncio.wait
Concurrency & Async

Meaning

Waits for multiple asyncio tasks to complete, splitting results into done and pending sets based on a timeout or completion condition. Addresses the need to process results as soon as any task finishes rather than blocking until all tasks complete. Reached for when you need to react to partial completion, enforce deadlines, or iteratively process finished work while letting remaining tasks continue.

Primary Function

Concurrency

Communicative Purpose

Enables non-blocking multiplexed waiting on async tasks with fine-grained control over when to return and how to handle incomplete work.

Pattern

done, pending = await asyncio.wait(tasks, timeout=seconds, return_when=condition)

Core Structure

done, pending = await asyncio.wait(..., timeout=..., return_when=...)

Função primária

Concurrency

Propósito comunicativo

Enables non-blocking multiplexed waiting on async tasks with fine-grained control over when to return and how to handle incomplete work.

Situações de gatilho

Network services: processing the first available response from redundant API calls. Task orchestration: running a batch of jobs with a hard deadline and cancelling stragglers. Pipeline processing: consuming completed items from a worker pool while keeping idle workers alive.

Contextos

asyncio-based Python applications, concurrent web scrapers, real-time data pipelines, server frameworks using cooperative multitasking.

Padrão

done, pending = await asyncio.wait(tasks, timeout=seconds, return_when=condition)

Estrutura central

done, pending = await asyncio.wait(..., timeout=..., return_when=...)

Slots de substituição

done: set of completed asyncio.Task objects, pending: set of still-running asyncio.Task objects, tasks: iterable of awaitables (coroutines or Tasks), seconds: float or None for no timeout, condition: asyncio.FIRST_COMPLETED | asyncio.FIRST_EXCEPTION | asyncio.ALL_COMPLETED

Colocados típicos

  • asyncio.gather
  • asyncio.create_task
  • asyncio.wait_for
  • task.cancel
  • task.result
  • asyncio.shield

Substituições comuns

  • asyncio.gather: returns results in order but waits for all by default and has no pending set — tradeoff is simpler API but no partial-completion handling. asyncio.wait_for: wraps a single coroutine with a timeout — tradeoff is single-target scope. asyncio.as_completed: yields futures as they finish via iterator — tradeoff is no timeout parameter and no pending set for cancellation.

Erros comuns

Passing bare coroutines instead of wrapping with asyncio.create_task first — causes coroutines to be implicitly scheduled but makes cancellation and introspection unreliable. Forgetting to cancel pending tasks after processing done set — leads to orphaned background work consuming resources. Accessing task.result() on a pending task — raises InvalidStateError since the task has not yet completed. Using return_when=asyncio.ALL_COMPLETED with a short timeout — returns immediately with empty done set and all tasks in pending, which is confusing if you expected partial results.

Similar / contraste

asyncio.gather: collects all results in order with no pending set. asyncio.as_completed: iterator-based yielding of futures as they finish. asyncio.TaskGroup: structured concurrency with automatic cancellation on any exception.

Interferências

Coming from JavaScript: may expect Promise.race semantics where only the winner is returned — asyncio.wait returns both done and pending sets requiring explicit cancellation. Coming from Go: may expect channel-based select behavior — asyncio.wait is a one-shot call, not a continuous multiplexer; you must loop manually. Coming from threading: may assume tasks run in parallel threads — asyncio tasks are cooperatively scheduled on one thread.

Família do chunk

  • asyncio.wait
  • asyncio.gather
  • asyncio.as_completed
  • asyncio.wait_for
  • asyncio.shield
  • asyncio.create_task

Nuance

Do not use when you need all results in order with exception propagation — asyncio.gather with return_exceptions=False is better. The timeout parameter raises no exception; it simply returns whatever has completed by the deadline, so you must check if done is empty. return_when=asyncio.FIRST_COMPLETED returns as soon as one task finishes, but if multiple tasks finish simultaneously, done may contain more than one task.

Efeito pragmático

Prevents indefinite blocking on slow or hung async operations, enables graceful degradation by processing partial results under time pressure, and allows systematic cleanup of unfinished work rather than abandoning it.

Dica de memória

Like a referee blowing the whistle at halftime — some players (tasks) have scored (done), others are still on the field (pending), and you decide what happens to each group.

Nota

Since Python 3.8, passing coroutines directly to asyncio.wait is deprecated; always wrap them with asyncio.create_task first. The function does not raise TimeoutError — it silently returns with whatever has completed by the deadline.

Upgrade path

asyncio.TaskGroup (Python 3.11+) for structured concurrency with automatic exception handling and cancellation propagation.

Frequência: MediumFormulaicidade: Semi-fixedTipo de construção: tuple_unpacking_await_assignmentPrioridade de aquisição: Active recallPrioridade de output: BothTag de espaçamento: Medium-term

Log in to save chunks.