Created
June 28, 2018 17:39
-
-
Save stevenwadejr/90d01b6b8b3c627291135d12849483ea to your computer and use it in GitHub Desktop.
Async Guzzle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once 'vendor/autoload.php'; | |
function client() | |
{ | |
static $client; | |
$client = $client ?? new GuzzleHttp\Client; | |
return $client; | |
} | |
function makeRequest(int $delay) | |
{ | |
echo "Making request [delay = $delay]\n"; | |
client()->getAsync('https://mockbin.org/delay/' . $delay) | |
->then(function() use ($delay) { | |
echo "Response received [delay = $delay]\n"; | |
}) | |
->wait(); | |
} | |
echo "Start\n"; | |
$time = -time(); | |
$delays = [5000, 2500, 1000, 500, 0]; | |
foreach ($delays as $delay) { | |
makeRequest($delay); | |
} | |
$time += time(); | |
echo "Finished\n"; | |
echo sprintf('Finished in %f seconds', $time); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once 'vendor/autoload.php'; | |
use GuzzleHttp\Promise\PromiseInterface; | |
function client() | |
{ | |
static $client; | |
$client = $client ?? new GuzzleHttp\Client; | |
return $client; | |
} | |
function makeRequest(int $delay): PromiseInterface | |
{ | |
echo "Making request [delay = $delay]\n"; | |
return client()->getAsync('https://mockbin.org/delay/' . $delay) | |
->then(function() use ($delay) { | |
echo "Response received [delay = $delay]\n"; | |
}); | |
} | |
echo "Start\n"; | |
$time = -time(); | |
$promises = [ | |
makeRequest(5000), | |
makeRequest(2500), | |
makeRequest(1000), | |
makeRequest(500), | |
makeRequest(0) | |
]; | |
\GuzzleHttp\Promise\unwrap($promises); | |
$time += time(); | |
echo "Finished\n"; | |
echo sprintf('Finished in %f seconds', $time); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The above outputs:
and