# Collecting Fallible Task Results

Independent tasks can complete in any order. Give each reply an identifier and
an explicit success or error value, then let one collector own aggregation.
This keeps the result protocol separate from scheduling order.

## A complete two-job batch

The first job doubles a nonnegative input. The second rejects a negative input.
Both send a `Reply`, so the collector receives two terminal outcomes instead
of waiting forever for a failed job to send a successful value.

```vex [async-batch-results.vx]
enum JobError { NegativeInput }
struct Reply { id: i32, result: Result<i32, JobError> }
async fn evaluate(value: i32): Result<i32, JobError> {
    if value < 0 { return Err(JobError.NegativeInput); }
    return Ok(value * 2);
}
async fn sendReply(id: i32, value: i32, output: Channel<Reply>) {
    let result = await evaluate(value);
    output.send(Reply { id: id, result: result });
}
fn main(): i32 {
    let output = Channel.new<Reply>(1);
    go { await sendReply(0, 21, output); };
    go { await sendReply(1, -3, output); };
    let! received = 0;
    let! success = 0;
    let! rejected = 0;
    while received < 2 {
        match output.recv() {
            Some(reply) => {
                received += 1;
                match reply.result {
                    Ok(value) => { if reply.id != 0 || value != 42 { return 1; } success += 1; },
                    Err(JobError.NegativeInput) => { if reply.id != 1 { return 2; } rejected += 1; },
                };
            },
            None => { return 3; },
        };
    }
    output.close();
    $println(success); $println(rejected);
    if success != 1 || rejected != 1 { return 4; }
    return 0;
}
```

Save as `async-batch-results.vx` and run `vex run async-batch-results.vx`.
Expected output is one successful result and one rejected input:

```text
1
1
```

The two workers can send in either order. `reply.id` lets the collector check
which input produced each result; the printed totals are order-independent.
The `Result` payload owns either the calculated value or the error enum.
`None` from `recv()` has a different meaning: the channel closed and drained
before all expected replies arrived.

The calculation completes immediately, but the protocol also explains where
an operation that suspends belongs: inside `evaluate`, awaited before its
reply is sent. Marking a function `async` does not make the two calls run in
parallel; the two `go` blocks are the scheduling operations.

## Backpressure and closure ownership

The output capacity is one. A sender may wait while the previous reply occupies
that slot; the collector creates space by receiving. Only the collector closes
the output, after consuming both expected replies. A worker must not close the
shared output after its own send because the other worker may still be using it.

This is a fixed batch: exactly two launched jobs each produce exactly one
terminal reply. For a variable-size stream, use a producer-completion protocol
such as [fan-in and shutdown](fan-in.md), then drain until
closure. A count of expected replies is not a cancellation or timeout policy.

The early returns in `main` are checks for this teaching example. In a service,
a collector that stops early must notify producers, handle unsuccessful
`send` results, and wait for their completion before releasing shared resources.
A panic, process termination, or worker that never sends is not converted into
an `Err` automatically.

## Preserve input order when needed

Carry an input index in each reply, as `id` does here. A single collector can
place each successful value or error into an indexed result collection. Emit
that collection in input order only after every expected index is complete.
For untrusted or retrying producers, also reject duplicate and out-of-range
indices; counting messages alone would not establish a complete batch.

Keep task-local calculations and result transfer separate from mutations of a
shared aggregate. The collector can own its counters or result storage without
introducing a lock around every worker update.

## Next steps

- [Async/Await and go](async.md)
- [Channels](channels.md)
- [Fan-in and channel shutdown](fan-in.md)
- [Result API](../types/result-api.md)
