ComponentsFuture::finally

Future::finally

(PHP 8.6+, True Async 1.0)

php
public function finally(callable $finally): Future

Registers a callback that executes when the Future completes regardless of the outcome --- success, error, or cancellation. The Future resolves with the same value or error as the original. Useful for releasing resources.

Parameters

finally — the function to execute on completion. Takes no arguments. Signature: function(): void.

Return value

Future — a new Future that will complete with the same value or error as the original.

Examples

Example #1 Releasing resources

php
<?php

use Async\Future;
use Async\FutureState;

$connection = openDatabaseConnection();

$state  = new FutureState();
$source = new Future($state);

\Async\spawn(function() use ($state, $connection) {
    $state->complete($connection->query("SELECT * FROM users"));
});

$future = $source
    ->finally(function() use ($connection) {
    $connection->close();
    echo "Connection closed\n";
});

$users = $future->await();

Example #2 Chaining with map, catch, and finally

php
<?php

use Async\Future;
use Async\FutureState;

$state  = new FutureState();
$source = new Future($state);

\Async\spawn(function() use ($state) {
    $state->complete(fetchDataFromApi());
});

$future = $source
    ->map(fn($data) => processData($data))
->catch(function(\Throwable $e) {
    error_log("Error: " . $e->getMessage());
    return [];
})
->finally(function() {
    echo "Operation completed\n";
});

$result = $future->await();

See also