Menu

Reference / Async

mapConcurrent()

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

Map $fn over $items with at most $limit calls running at once.

The everyday "fetch 1000 URLs, 10 at a time". Results are keyed like $items; the first failure cancels the rest and propagates (fail-fast, like awaitAll()).

$pages = Async\mapConcurrent($urls, fn($u) => file_get_contents($u), 10);

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

mixed[] — the results, keyed like $items

Throws

\Throwable
the first failure

Example

use function Async\async;
use function Async\delay;
use function Async\mapConcurrent;

$inFlight = 0;
$peak = 0;

$squares = async(function () use (&$inFlight, &$peak) {
    // Square five numbers, never more than two at a time.
    return mapConcurrent([1, 2, 3, 4, 5], function (int $n) use (&$inFlight, &$peak) {
        $inFlight++;
        $peak = max($peak, $inFlight);
        delay(0.01);
        $inFlight--;
        return $n * $n;
    }, 2);
});

echo implode(",", $squares), "\n";
echo "peak in flight: $peak\n";

Output

1,4,9,16,25
peak in flight: 2

See also: mapSettled, Semaphore

View source