I had success running concurrent HTTP requests with this code:
function do_requests(\GuzzleHttp\Client $client, int $total): \Generator
{
for ($i = 0; $i < $total; $i++) {
$uri = "https://httpbin.org/anything?q=$i";
$promise = $client->getAsync($uri);
yield ['uri' => $uri, 'response' => $promise->wait()->getBody()->getContents()];
}
}
$client = new \GuzzleHttp\Client();
foreach (do_requests($client, 100) as $do_request) {
var_dump($do_request);
}
However, I must ensure a maximum of 25 concurrent requests, so I tried this code:
function prepare_requests(int $total): \Generator
{
for ($i = 0; $i < $total; $i++) {
$uri = "https://httpbin.org/anything?q=$i";
yield new \GuzzleHttp\Psr7\Request('GET', $uri);
}
}
function do_pool_requests(\GuzzleHttp\Client $client, int $total): \Generator
{
$pool = new \GuzzleHttp\Pool($client, prepare_requests($total), ['concurrency' => 25]);
/** @var \GuzzleHttp\Psr7\Response $response */
foreach ($pool->promise()->wait() as $response) {
yield ['headers' => $response->getHeaders(), 'response' => $response->getBody()->getContents()];
}
}
$client = new \GuzzleHttp\Client();
foreach (do_pool_requests($client, 100) as $do_request) {
var_dump($do_request);
}
This second example fails, though. It raises the warning PHP Warning: foreach() argument must be of type array|object, null given
and points to this line: foreach ($pool->promise()->wait() as $response) {
.
What am I doing wrong?