TaskSet::spawnWithKey

(PHP 8.6+, True Async 1.0)

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

Adds a callable to the set with a specified key. The key is used in the results array and during iteration via foreach.

Parameters

key
Result key. Must be unique within the set.
task
Callable to execute.
args
Arguments passed to the callable.

Errors

Examples

Example #1 Named tasks

<?php

use Async\TaskSet;

spawn(function() {
    $set = new TaskSet();

    $set->spawnWithKey('user',   fn() => fetchUser($id));
    $set->spawnWithKey('orders', fn() => fetchOrders($id));

    $set->seal();
    $data = $set->joinAll()->await();

    echo $data['user']['name'];
    echo count($data['orders']);
});

See Also