Skip to content

Instantly share code, notes, and snippets.

@stevenwadejr
Last active May 8, 2018 13:56
Show Gist options
  • Save stevenwadejr/6b51eb95e3743f6b0e13b887e35b7180 to your computer and use it in GitHub Desktop.
Save stevenwadejr/6b51eb95e3743f6b0e13b887e35b7180 to your computer and use it in GitHub Desktop.
HTTP Coroutines
<?php
function makeRequest(int $delay)
{
$client = new Amp\Artax\DefaultClient;
echo "Making request [delay = $delay]\n";
$response = yield $client->request('https://mockbin.org/delay/' . $delay);
echo "Response received [delay = $delay]\n";
$body = yield $response->getBody();
print_r(json_decode($body, true));
}
$requests = [
Amp\call('makeRequest', 5000),
Amp\call('makeRequest', 500)
];
echo "Start\n";
Amp\Promise\wait(Amp\Promise\all($requests));
echo "Waiting...\n";
<?php
use Function GuzzleHttp\Promise\coroutine;
function call(callable $callback, ...$args)
{
return coroutine(function() use ($callback, $args) {
return $callback(...$args);
});
}
function client()
{
static $client;
$client = $client ?? new GuzzleHttp\Client;
return $client;
}
function makeRequest(int $delay)
{
$client = new GuzzleHttp\Client;
echo "Making request [delay = $delay]\n";
// $response = yield $client->getAsync('https://mockbin.org/delay/' . $delay);
$response = yield client()->getAsync('https://mockbin.org/delay/' . $delay);
echo "Response received [delay = $delay]\n";
$result = json_decode($response->getBody()->getContents(), true);
print_r($result);
}
echo "Start\n";
$promises = [
call('makeRequest', 5000),
call('makeRequest', 500),
call('makeRequest', 0)
];
\GuzzleHttp\Promise\unwrap($promises);
echo "Finished\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment