Menu

Reference / Async

awaitAll()

function
function awaitAll(Task ...$tasks): array

Wait for every task and return their results keyed by input position.

Fail-fast: the first failure cancels the tasks still running, joins them, and rethrows that error, which is the structured-concurrency contract rather than Promise.allSettled. Every input is claimed before parking, so a sibling that fails while this call is parked is not mistaken for an unhandled failure and escalated behind your back.

Ownership: on failure this cancels only the tasks owned by the caller's scope or one nested inside it. A task borrowed from an enclosing scope, which someone else may still be awaiting, is left alone. With no tasks it returns an empty array.

Parameters

...$tasks Task
the tasks to wait for

Returns

mixed[] — results keyed by input position (0..N-1)

Throws

\Throwable
the first failure among the tasks

Example

use function Async\async;
use function Async\awaitAll;
use function Async\delay;
use function Async\spawn;

async(function () {
    // The tasks finish in the order c, b, a ...
    $a = spawn(function () { delay(0.03); return "a"; });
    $b = spawn(function () { delay(0.02); return "b"; });
    $c = spawn(function () { delay(0.01); return "c"; });

    // ... but results are keyed by input position.
    echo implode(",", awaitAll($a, $b, $c)), "\n";

    // Fail-fast: the first failure cancels the others and is rethrown.
    $ok = spawn(function () { delay(10.0); return "never"; });
    $bad = spawn(function () { delay(0.01); throw new RuntimeException("boom"); });
    try {
        awaitAll($ok, $bad);
    } catch (RuntimeException $e) {
        echo "failed: ", $e->getMessage(), "\n";
    }
    echo "slow task cancelled: ", $ok->isDone() ? "yes" : "no", "\n";
});

Output

a,b,c
failed: boom
slow task cancelled: yes

See also: awaitAllSettled, awaitAny, mapConcurrent

View source