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
foreachsuspends the current coroutine until the next result is available- The key is the same as assigned via
spawn()orspawnWithKey() - The value is an array
[mixed $result, ?Throwable $error]:- Success:
[$result, null] - Error:
[null, $error]
- Success:
- Iteration ends when the group is sealed and all tasks have been processed
- If the group is not sealed,
foreachsuspends waiting for new tasks
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
- TaskGroup::seal — Seal the group
- TaskGroup::all — Wait for all tasks
- TaskGroup::getResults — Get an array of results