Menu

Reference / Async

group()

function
function group(callable $body): mixed

Open a child scope and return the body's value.

The everyday form of TaskGroup::run(). It returns only once every task spawned inside has settled; the first failure cancels the rest, joins them, and propagates.

$total = Async\group(function (TaskGroup $g) {
    $a = $g->spawn(fn() => fetch(1));
    $b = $g->spawn(fn() => fetch(2));
    return $a->await() + $b->await();
});

Parameters

$body callable
receives the new TaskGroup; its return value is returned

Returns

mixed — the body's return value

Throws

\Throwable
the first failure in the scope

Example

use Async\TaskGroup;
use function Async\async;
use function Async\delay;
use function Async\group;

async(function () {
    // group() opens a child scope. It returns the body's value, but only
    // after every task spawned inside has settled.
    $answer = group(function (TaskGroup $g) {
        $g->spawn(function () {
            delay(0.02);
            echo "second child done\n";
        });
        $g->spawn(function () {
            delay(0.01);
            echo "first child done\n";
        });
        echo "body finished\n";
        return 42;
    });

    echo "group returned $answer\n";
});

Output

body finished
first child done
second child done
group returned 42

Example

use Async\CancelledException;
use Async\TaskGroup;
use function Async\async;
use function Async\delay;

try {
    async(function () {
        TaskGroup::run(function (TaskGroup $g) {
            $g->spawn(function () {
                try {
                    delay(10.0);
                } catch (CancelledException $e) {
                    echo "sibling cancelled\n";
                    throw $e;
                }
            });
            $g->spawn(function () {
                delay(0.01);
                throw new RuntimeException("child failed");
            });
        });
        echo "not reached\n";
    });
} catch (RuntimeException $e) {
    // The first failure cancelled the sibling, the scope joined it, and the
    // original exception came out of the scope.
    echo "caught: ", $e->getMessage(), "\n";
}

Output

sibling cancelled
caught: child failed

See also: TaskGroup, timeout

View source