2019-11-22 19:34:10 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
// https://xrg.io/tests/promises
|
|
|
|
|
|
|
|
require_once(dirname(__FILE__) .'/vendor/autoload.php');
|
|
|
|
|
|
|
|
// lib.php, helper functions
|
|
|
|
Lib\plain();
|
2019-11-22 19:40:50 +00:00
|
|
|
Lib\printf('https://sergio.am/code/www-tests');
|
2019-11-22 19:34:10 +00:00
|
|
|
|
|
|
|
use GuzzleHttp\Client;
|
|
|
|
use GuzzleHttp\Pool;
|
|
|
|
|
|
|
|
Lib\printf('client');
|
|
|
|
|
|
|
|
$client = new Client();
|
|
|
|
|
|
|
|
Lib\printf('requests');
|
|
|
|
|
|
|
|
$requests = function ($n) use ($client) {
|
|
|
|
$uri = 'https://xrg.io/tests/promises/sleep.php?';
|
|
|
|
|
|
|
|
for ($i = 0; $i < $n; $i++) {
|
|
|
|
yield function() use ($client, $uri, $i) {
|
2019-11-22 19:40:50 +00:00
|
|
|
Lib\printf(' yield i='. $i);
|
|
|
|
return $client->getAsync($uri . http_build_query(['i' => $i, 's' => random_int(1, 5)]));
|
2019-11-22 19:34:10 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
Lib\printf('pool');
|
|
|
|
|
|
|
|
$pool = new Pool($client, $requests(3), [
|
|
|
|
'concurrency' => 5,
|
|
|
|
'fulfilled' => function ($response, $index) {
|
|
|
|
Lib\printf(' i='. $index .' '. $response->getBody());
|
|
|
|
},
|
|
|
|
'rejected' => function ($reason, $index) {
|
|
|
|
Lib\printf(' '. $index .' '. $reason);
|
|
|
|
},
|
|
|
|
]);
|
|
|
|
|
|
|
|
Lib\printf('promise');
|
|
|
|
// Initiate the transfers and create a promise
|
|
|
|
$promise = $pool->promise();
|
|
|
|
|
|
|
|
Lib\printf('wait');
|
|
|
|
// Force the pool of requests to complete.
|
|
|
|
$promise->wait();
|
|
|
|
|
|
|
|
Lib\printf('end');
|