Skip to content

Instantly share code, notes, and snippets.

@bwoebi
Forked from chrisleavoy/example.php
Last active June 1, 2016 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bwoebi/7cba5729647b7ee76fcc337a06e0a5ed to your computer and use it in GitHub Desktop.
Save bwoebi/7cba5729647b7ee76fcc337a06e0a5ed to your computer and use it in GitHub Desktop.
Amp\wait LogicException
<?php
require_once dirname(__DIR__) . '/vendor/autoload.php';
function resolve($pluginName, $x)
{
$saneDefaults = [
'types' => \Amp\Dns\Record::A, 'server' => "8.8.8.{$x}", 'timeout' => 1000, 'tries' => 1,
'cache' => false
];
$result = (yield \Amp\Dns\resolve($pluginName, $saneDefaults));
yield new \Amp\CoroutineResult($result);
return;
}
function analyze($pluginName)
{
$x = rand(7,8);
try {
$promise = yield resolve($pluginName, $x));
$result = yield($promise);
} catch (\Exception $e) {
$result = "{$pluginName} timed out {$x}";
echo $result . "\n";
}
return new \Amp\CoroutineResult($result);
}
// if you want to access this directly from within sync code, write \Amp\wait(analyzePlugin($plugin))
// but do *never* do that from within async code
function analyzePlugin($pluginName)
{
$start = microtime(true);
echo("start $pluginName " . $start . "\n");
$r = \Amp\resolve(analyze($pluginName));
$r->when(function() {
echo("stop $pluginName " . (microtime(true) - $start) . "\n");
});
return $r;
}
function analyzePluginsAsync()
{
$registeredPlugins = ['google.ca', 'yahoo.com', 'textnow.com'];
$promises = [];
foreach ($registeredPlugins as $pluginName) {
$promises []= analyzePlugin($pluginName);
}
return \Amp\all($promises);
}
$start = microtime(true);
$result = \Amp\wait(analyzePluginsAsync());
echo "total: " . (microtime(true) - $start) . "\n";
// var_dump($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment