TaskGroup::spawnWithKey

(PHP 8.6+, True Async 1.0)

public TaskGroup::spawnWithKey(string|int $key, callable $task, mixed ...$args): void

Adds a callable to the group with the specified key. The task result will be accessible by this key in all(), getResults(), and during iteration.

Parameters

key
The task key. A string or integer. Duplicates are not allowed.
task
The callable to execute.
args
Arguments passed to the callable.

Errors

Throws Async\AsyncException if the group is sealed or the key already exists.

Examples

Example #1 Named tasks

<?php

use Async\TaskGroup;

spawn(function() {
    $group = new TaskGroup();

    $group->spawnWithKey('profile', fn() => ['name' => 'John']);
    $group->spawnWithKey('orders', fn() => [101, 102, 103]);

    $group->seal();
    $results = $group->all();

    var_dump($results['profile']); // array(1) { ["name"]=> string(4) "John" }
    var_dump($results['orders']);   // array(3) { [0]=> int(101) ... }
});

See Also