PHP does not have async/wait syntax. Is it possible to add a function to call the main loop code so that we can write synchronous code instead of callback functions.
<?php
class Loop {
function loopTick () {
// ...
}
function run () {
while (loopTick()) {}
}
}
// function wait run the function loopTick likely $loop->run(), and block the current thread until promise settled.
function waitPromiseSettled ($promise) {
$rejected = false;
$resolved = false;
$error = null;
$ret = null;
$promsie->then(function ($val) use (&$resolved, &$ret) {
$ret = $val;
$resolved = true;
})->catch(function ($err) use (&$rejected, &$error) {
$error = $err;
$rejected = true;
});
while (loopTick()) {
if ($resolved) {
return $ret;
} else if ($rejected) {
throw $error;
}
}
throw new Exception("...");
}
class Promise {
function resolve () {
// ...
}
function reject () {
// ...
}
function wait () {
return waitPromiseSettled($this);
}
}
// coding sync
$value = new Promise(function (/* ... */) { /* ... */ })->wait();