phasync
phasync / finally

Method

phasync::finally

Registers $fn to run when the current coroutine ends, or when the nested run() it is in returns.

Description#

public static phasync::finally(
    Closure $fn
): void

The callbacks run last registered first, and each runs even when another threw. They are for releasing what a coroutine acquired, where a try {} finally {} does not fit. Their waits are not cancelled, so cleanup that does I/O completes even when the coroutine was cancelled.

Which callbacks run when depends on where finally() is called. Inside a run() nested in a coroutine, they run as $fn returns, in the calling coroutine and still in the run's frame, also when $fn threw, and before run() waits for the coroutines $fn started. Otherwise they run when the coroutine ends, in a coroutine of their own.

Parameters#

$fn Closure

Errors / Exceptions#

ExceptionWhen
LogicExceptionOutside a coroutine

Examples#

Example 1
phasync::run(function () {
    phasync::go(function () {
        phasync::finally(fn () => print("registered first\n"));
        phasync::finally(fn () => print("registered second\n"));   // prints first
        phasync::sleep(0.1);
    });
});

See also#

  • phasync::runRuns $fn and returns its result once it and every coroutine started inside it have ended.
  • phasync::cancelCancels a coroutine with a CancelledException.