Menu

Reference / Async

awaitAllSettled()

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

Wait for every task and report how each one turned out.

Never throws on a task failure and never cancels anything: the counterpart to awaitAll() for the "fetch a hundred of them and tell me which failed" shape. Reporting a failure counts as handling it, so it is not escalated to the enclosing scope.

Parameters

...$tasks Task
the tasks to wait for

Returns

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

Example

use function Async\async;
use function Async\awaitAllSettled;
use function Async\delay;
use function Async\mapSettled;
use function Async\spawn;

async(function () {
    $a = spawn(function () { delay(0.01); return "fine"; });
    $b = spawn(function () { throw new RuntimeException("broken"); });

    // Nothing is cancelled and nothing is thrown: every outcome is reported.
    foreach (awaitAllSettled($a, $b) as $i => $s) {
        echo "$i: ", $s->ok ? "ok {$s->value}" : "error {$s->error->getMessage()}", "\n";
    }

    $results = mapSettled([2, 0, 4], function (int $n) {
        if ($n === 0) {
            throw new InvalidArgumentException("zero");
        }
        return 8 / $n;
    }, 2);
    foreach ($results as $i => $s) {
        echo "$i: ", $s->ok ? "ok {$s->value}" : "error {$s->error->getMessage()}", "\n";
    }
});

Output

0: ok fine
1: error broken
0: ok 4
1: error zero
2: ok 2

See also: awaitAll, mapSettled

View source