www-tests/promises/index.php

55 lines
1.3 KiB
PHP

<?php
// https://xrg.io/tests/promises
require_once(dirname(__FILE__) .'/vendor/autoload.php');
// lib.php, helper functions
Lib\plain();
Lib\printf('https://sergio.am/code/www-tests');
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Promise\EachPromise;
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) {
Lib\printf(' yield i='. $i);
return $client->getAsync($uri . http_build_query(['i' => $i, 's' => random_int(1, 5)]));
};
}
};
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');