TaskGroup::getIterator

(PHP 8.6+, True Async 1.0)

public TaskGroup::getIterator(): Iterator

Returns an iterator that yields results as tasks complete. TaskGroup implements IteratorAggregate, so you can use foreach directly.

Iterator Behavior

Important: Without calling seal(), iteration will wait indefinitely.

Examples

Example #1 Processing results as they become ready

<?php

use Async\TaskGroup;

spawn(function() {
    $group = new TaskGroup(concurrency: 3);

    for ($i = 0; $i < 10; $i++) {
        $group->spawn(fn() => fetchUrl($urls[$i]));
    }
    $group->seal();

    foreach ($group as $key => [$result, $error]) {
        if ($error !== null) {
            echo "Task $key failed: {$error->getMessage()}\n";
            continue;
        }
        echo "Task $key done\n";
    }
});

Example #2 Iteration with named keys

<?php

use Async\TaskGroup;

spawn(function() {
    $group = new TaskGroup();

    $group->spawnWithKey('users', fn() => fetchUsers());
    $group->spawnWithKey('orders', fn() => fetchOrders());
    $group->seal();

    foreach ($group as $key => [$result, $error]) {
        if ($error === null) {
            echo "$key: received " . count($result) . " records\n";
        }
    }
});

See Also