Skip to content

Instantly share code, notes, and snippets.

@devhammed
Created May 20, 2025 17:01
Show Gist options
  • Save devhammed/0fcd636c39a6ad47688404587c361796 to your computer and use it in GitHub Desktop.
Save devhammed/0fcd636c39a6ad47688404587c361796 to your computer and use it in GitHub Desktop.
Async/Await in PHP
<?php
function async(Closure $task): Closure
{
static $resolved = [];
if ( ! extension_loaded('pcntl') || ! extension_loaded('posix')) {
return $task;
}
$id = uniqid();
$path = implode(DIRECTORY_SEPARATOR, [
sys_get_temp_dir(),
'php_async_'.$id,
]);
$pid = pcntl_fork();
if ($pid === -1) {
throw new RuntimeException('Failed to fork process.');
}
if ($pid === 0) {
if (file_exists($path)) {
unlink($path);
}
$result = $task($id);
$pipe = fopen($path, 'w');
fwrite($pipe, serialize($result));
fclose($pipe);
exit(0);
}
return function () use ($pid, $id, $path, &$resolved) {
if (isset($resolved[$id])) {
return $resolved[$id];
}
pcntl_waitpid($pid, $status);
$pipe = fopen($path, 'r');
$serialized = stream_get_contents($pipe);
fclose($pipe);
if (file_exists($path)) {
unlink($path);
}
return $resolved[$id] ??= unserialize($serialized);
};
}
function await(Closure|array $tasks): mixed
{
if ( ! is_array($tasks)) {
return $tasks();
}
return array_map(
fn(Closure $task): mixed => $task(), $tasks,
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment