PHP code example of sof3 / await-generator
1. Go to this page and download the library: Download sof3/await-generator library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
sof3 / await-generator example snippets
load_data(function($data) {
$init = count($data) === 0 ? init_data(...) : fn($then) => $then($data);
$init(function($data) {
$output = [];
foreach($data as $k => $datum) {
processData($datum, function($result) use(&$output, $data) {
$output[$k] = $result;
if(count($output) === count($data)) {
createQueries($output, function($queries) {
$run = function($i) use($queries, &$run) {
runQuery($queries[$i], function() use($i, $queries, $run) {
if($i === count($queries)) {
$done = false;
commitBatch(function() use(&$done) {
if(!$done) {
$done = true;
echo "Done!\n";
}
});
onUserClose(function() use(&$done) {
if(!$done) {
$done = true;
echo "User closed!\n";
}
});
onTimeout(function() use(&$done) {
if(!$done) {
$done = true;
echo "Timeout!\n";
}
});
} else {
$run($i + 1);
}
});
};
});
}
});
}
});
});
$data = yield from load_data();
if(count($data) === 0) $data = yield from init_data();
$output = yield from Await::all(array_map(fn($datum) => processData($datum), $data));
$queries = yield from createQueries($output);
foreach($queries as $query) yield from runQuery($query);
[$which, ] = yield from Await::race([
0 => commitBatch(),
1 => onUserClose(),
2 => onTimeout(),
])
echo match($which) {
0 => "Done!\n",
1 => "User closed!\n",
2 => "Timeout!\n",
};
function oldApi($args, Closure $onSuccess) {
Await::f2c(fn() => $onSuccess(yield from newApi($args)));
}
function newApi($args, Closure $onSuccess, Closure $onError) {
Await::f2c(function() use($onSuccess, $onError) {
try {
$onSuccess(yield from newApi($args));
} catch(Exception $ex) {
$onError($ex);
}
});
}
yield from Await::promise(fn($resolve, $reject) => oldFunction($args, $resolve, $reject));