Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 34 additions & 2 deletions lib/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,23 @@ function await(Promise|array $promise): mixed
$promise = Promise\all($promise);
}

$fiber = \Fiber::this();
$fiber = \Fiber::getCurrent();
$resolved = false;

if ($fiber) { // Awaiting from within a fiber.
if ($fiber === Loop::getFiber()) {
throw new \Error(\sprintf('Cannot call %s() within an event loop callback', __FUNCTION__));
}

$promise->onResolve(static function (?\Throwable $exception, mixed $value) use (&$resolved, $fiber): void {
$hash = spl_object_hash($fiber);
$level = ob_get_level();

if ($level)
{
Loop::setState($hash . '-key', $level);
}

$promise->onResolve(static function (?\Throwable $exception, mixed $value) use (&$resolved, $fiber, $hash): void {
$resolved = true;

if ($exception) {
Expand All @@ -45,8 +53,32 @@ function await(Promise|array $promise): mixed
});

try {
if (Loop::getState($hash . '-key'))
{
$content = ob_get_contents();

if ($content !== '')
{
Loop::setState($hash . '-content', $content);
}

ob_end_clean();
}

// Suspend the current fiber until the promise is resolved.
$value = \Fiber::suspend();

if (Loop::getState($hash . '-key'))
{
ob_start();
$content = Loop::getState($hash . '-content');

if (!is_null($content))
{
echo $content;
Loop::setState($hash . '-content', null);
}
}
} finally {
if (!$resolved) {
// $resolved should only be false if the fiber was manually resumed outside of the callback above.
Expand Down