Menu

Reference / Async

mapSettled()

function
function mapSettled(array $items, callable $fn, int $limit): array

mapConcurrent() that collects outcomes instead of failing fast.

Runs at most $limit calls at once and returns one Settled per input position. A call that throws becomes a failed Settled and does not cancel its siblings.

Parameters

$items mixed[]
$fn callable
called as $fn($item, $key) for each item
$limit int
maximum calls in flight; values below 1 are raised to 1

Returns

Settled[] — one outcome per item, keyed like $items

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: mapConcurrent, awaitAllSettled

View source