diff --git a/lib/functions.php b/lib/functions.php index 9945bc4b..7725b762 100644 --- a/lib/functions.php +++ b/lib/functions.php @@ -25,7 +25,7 @@ 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. @@ -33,7 +33,15 @@ function await(Promise|array $promise): mixed 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) { @@ -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.