KomponentenFuture::finally

Future::finally

(PHP 8.6+, True Async 1.0)

php
public function finally(callable $finally): Future

Registriert einen Callback, der bei Abschluss des Future ausgeführt wird, unabhängig vom Ergebnis --- Erfolg, Fehler oder Abbruch. Das Future wird mit demselben Wert oder Fehler wie das Original aufgelöst. Nützlich zur Freigabe von Ressourcen.

Parameter

finally — die Funktion, die bei Abschluss ausgeführt wird. Nimmt keine Argumente entgegen. Signatur: function(): void.

Rückgabewert

Future — ein neues Future, das mit demselben Wert oder Fehler wie das Original abgeschlossen wird.

Beispiele

Beispiel #1 Ressourcen freigeben

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 "Verbindung geschlossen\n";
});

$users = $future->await();

Beispiel #2 Verkettung mit map, catch und 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("Fehler: " . $e->getMessage());
    return [];
})
->finally(function() {
    echo "Operation abgeschlossen\n";
});

$result = $future->await();

Siehe auch