php-async/bin/app.php

45 lines
832 B
PHP
Raw Normal View History

2019-01-16 01:10:54 +01:00
#!/usr/bin/php
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use function Joop\Asynchronous\async;
use Joop\Asynchronous\Promise;
/**
* @param Promise[] $promises
*/
function awaitPromises(array &$promises)
{
2019-01-16 01:10:54 +01:00
foreach ($promises as $index => $promise) {
if ($promise->isResolved()) {
2019-01-16 01:10:54 +01:00
unset($promises[$index]);
if (!$promise->isEmpty() && !$promise->isError())
print($promise->getValue() . PHP_EOL);
2019-01-16 01:10:54 +01:00
}
}
}
/*
* Example of asynchronous processing in PHP
*/
$process = function ($i) {
$delayMicroseconds = (5 - $i) * 1000000;
usleep($delayMicroseconds);
return sprintf(
'PID %-5d slept for %.1f seconds',
getmypid(), $delayMicroseconds / 1000000
);
};
2019-01-16 01:10:54 +01:00
$promises = [];
foreach (range(0, 5) as $i)
$promises[] = async($process, $i);
2019-01-16 01:10:54 +01:00
while (count($promises) > 0)
awaitPromises($promises);