phasync
phasync / await

Method

phasync::await

Waits for a coroutine or a promise, and returns its result or throws the exception it ended with.

Description#

public static phasync::await(
    object $fiberOrPromise,
    float $timeout = PHP_FLOAT_MAX
): mixed

A coroutine can be awaited any number of times, by any number of coroutines, and each call returns the same value or throws the same exception. Awaiting a failed coroutine counts as handling its failure: it no longer fails the run. A timeout throws in the caller only: the awaited coroutine keeps running.

Given a SelectableInterface (a channel end, a WaitGroup, a StringBuffer, a RateLimiter), it waits until the object isReady() and returns the object. How a timeout ends depends on the object, see its await(). Given an object with a then() method, such as a promise from another library, it waits until the promise settles, and returns its value or throws its rejection; a rejection that is not a Throwable is thrown as an Exception with its string form as message.

Parameters#

$fiberOrPromise object
A coroutine from go() or run(), a SelectableInterface, or a promise-like object
$timeout float = PHP_FLOAT_MAX
Seconds to wait at most

Return values#

The coroutine's return value; for a SelectableInterface, the object mixed

Errors / Exceptions#

ExceptionWhen
TimeoutExceptionIf a coroutine or promise does not end within $timeout
InvalidArgumentExceptionFor an object that is none of the above
LogicExceptionFor a Fiber that phasync did not start
ThrowableWhat the coroutine threw

Examples#

Example 1
phasync::run(function () {
    $fiber = phasync::go(function () { phasync::sleep(0.1); return 'result'; });

    try {
        phasync::await($fiber, 0.01);
    } catch (phasync\TimeoutException) {
        echo "not yet\n";
    }
    echo phasync::await($fiber), "\n";   // result
});

See also#

  • phasync::goStarts $fn as a coroutine in the current frame and scope, and returns it, without waiting for it.
  • phasync::cancelCancels a coroutine with a CancelledException.
  • phasync::runRuns $fn and returns its result once it and every coroutine started inside it have ended.