Scope::awaitCompletion

(PHP 8.6+, True Async 1.0)

public function awaitCompletion(Awaitable $cancellation): void

Waits for all active coroutines in the scope to complete. Zombie coroutines are not considered when waiting. The $cancellation parameter allows the wait to be interrupted early.

Parameters

cancellation — an Awaitable object that, when triggered, will interrupt the wait.

Return Value

No value is returned.

Examples

Example #1 Waiting for all coroutines to complete

<?php

use Async\Scope;
use function Async\timeout;

$scope = new Scope();

$scope->spawn(function() {
    \Async\delay(1000);
    echo "Task 1 completed\n";
});

$scope->spawn(function() {
    \Async\delay(2000);
    echo "Task 2 completed\n";
});

// Wait for completion with a 5-second timeout
$scope->awaitCompletion(timeout(5000));
echo "All tasks done\n";

Example #2 Interrupting the wait

<?php

use Async\Scope;
use function Async\timeout;

$scope = new Scope();

$scope->spawn(function() {
    \Async\delay(60_000); // Very long task
});

try {
    $scope->awaitCompletion(timeout(3000));
} catch (\Async\CancelledException $e) {
    echo "Wait interrupted by timeout\n";
    $scope->cancel();
}

See Also