Skip to content

Core\Task::map

Core\Task::map(
    array<T> $items,
    callable(T, string): U $fn,
    {limit?: uint, deadline?: Core\Time\Duration},
): array<U>

Core\Task::map() calls one function for each element of an array, and runs the calls at the same time. It waits until every call has finished.

The result is an array with the same keys, in the same order, as the array you give it. The order does not change when a later call finishes first. Your function gets the value and, if it declares a second parameter, the key as a string. Use it when a program has a list of slow jobs of the same kind, such as checking many web addresses or loading many files.

If one call throws an error, the other calls are stopped, and map throws that error. The option limit sets how many calls run at the same time. The option deadline is a time limit for the whole call. When it runs out, the call throws a TimeoutError. The deadline is checked while the calls wait. A call that never waits, such as an endless loop, is stopped by the request's cpu_time limit instead.

The examples below show that the order stays the same, a function that uses the key, and many links checked with a limit and a time limit.

Parameters

  • $itemsarray<T>The array. Each element is given to $fn in a task of its own.
  • $fncallable(T, string): UThe function to call. It gets ($value, $key), and it may declare only $value. The key is always a string. Its return type is the type of each element of the result.

Options

  • limituintoptionalThe most tasks that run at the same time. The other tasks wait until one finishes. Without it, every task starts at once.
  • deadlineCore\Time\DurationoptionalThe time limit for the whole call, not for each task. Without it, the request's [limits] wall_time setting is the limit.

Return value

Returns array<U>. An array with what $fn returned for each element, under the element's own key. An empty $items gives an empty array. No task is still running when the call returns. If a task throws an error, the other tasks are stopped, and the call throws that same error.

Errors

  • LogicErrorWhen limit is 0. No task could start, so the call could never finish.
  • TimeoutErrorWhen deadline runs out before every task has finished. Every task is stopped first, and the call waits until they have stopped.

Examples

The order stays the same

<?nvs
// Shows that the result keeps the order of the array, even when a later task finishes first.
// The first file takes the longest time to load, and the last file the shortest.
array<int> $waits = [30, 20, 10];
// `Core\Task::map` calls the function once for each element, at the same time.
var $loaded = Core\Task::map($waits, fn(int $ms): string => {
Core\Time::sleep(Core\Time\Duration::milliseconds($ms));
return 'file loaded in ' . $ms . 'ms';
});
// The results are in the order of `$waits`. This prints the 30ms line first.
foreach ($loaded as string $index => string $line) {
echo $index, ': ', $line, "\n";
}
Output
0: file loaded in 30ms
1: file loaded in 20ms
2: file loaded in 10ms

Use the key too

<?nvs
// Shows a function that uses both the value and the key of each element.
// The keys are the names of the shops, and the values are their stock counts.
array<int> $stock = ['north' => 12, 'south' => 0, 'west' => 7];
// A function with a second parameter gets the key. The key is always a `string`.
var $report = Core\Task::map($stock, fn(int $count, string $shop): string =>
$count > 0 ? $shop . ' has ' . $count : $shop . ' is empty');
// The result has the same keys. This prints `south is empty` on the second line.
foreach ($report as string $shop => string $line) {
echo $line, "\n";
}
Output
north has 12
south is empty
west has 7

Check many links with a time limit

<?nvs
// Shows how to check many links at the same time, with a limit and a time limit.
class Links
{
// A real program sends a request here. This one waits, and then
// returns a status code.
public static function check(string $url): int
{
Core\Time::sleep(20ms);
return Core\Str::endsWith($url, '/old') ? 404 : 200;
}
public static function report(array<string> $urls, Core\Time\Duration $limit): string
{
try {
// `limit: 2` runs at most two checks at the same time.
// `deadline` is the time limit for all the checks together.
var $codes = Core\Task::map(
$urls,
fn(string $url): int => Links::check($url),
{ limit: 2, deadline: $limit },
);
array<string> $broken = [];
foreach ($codes as string $index => int $code) {
if ($code != 200) {
$broken[] = $urls[$index];
}
}
return 'broken: ' . Core\Str::join($broken, ', ');
} catch (TimeoutError $e) {
// When the time is over, every check is stopped and
// `Core\Task::map` throws a `TimeoutError`.
return 'the links could not be checked in time';
}
}
}
array<string> $urls = [
'https://example.com/',
'https://example.com/shop',
'https://example.com/old',
'https://example.com/blog',
];
// Two seconds is enough time, so this prints the one broken link.
echo Links::report($urls, 2s), "\n";
// Five milliseconds is not enough, so this prints the error text.
echo Links::report($urls, 5ms), "\n";
Output
broken: https://example.com/old
the links could not be checked in time