Menu

Reference / Async

Settled

finalclass
final class Settled

How one task turned out, when you asked for the outcome rather than the value.

Returned by Task::join(), awaitAllSettled() and mapSettled(). ok decides which of value and error is meaningful: on success error is null, on failure value is null.

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: awaitAllSettled, mapSettled, Task::join

Methods

__construct()Build an outcome.

__construct()#source

function __construct(public bool $ok, public mixed $value, public ?\Throwable $error)

Build an outcome.

Parameters

$ok bool
true when the task returned normally
$value mixed
the task's return value when $ok
$error ?\Throwable
what the task threw when not $ok

View source