How to send multiple requests at once ReactPHP?

1.3k Views Asked by At

I am using guzzle to send some requests:

$response = $this->client->request(new SomeObject());

using the class below

...
public function request(Request $request)
{
    return $this->requestAsync($request)->wait();
}

// Here I'm using Guzzle Async, but I can remove that is needed
public function requestAsync(Request $request)
{
    $promise = $this->http->requestAsync($request->getMethod(), $request->getUri());

    $promise = $promise->then(
        function (ResponseInterface $response) use ($request) {
            return $response;
        }
    );

    return $promise;
}
...

I would like to use ReactPHP to send multiple requests at once in a foreach loop:

$requests = [];
foreach ($data as $value) {
    $requests[] = $this->client->request(new SomeObject());
}

// pass $requests to ReactPHP here and wait on the response

Any ideas?

1

There are 1 best solutions below

2
On

First of all, you don't need ReactPHP to use parallel HTTP requests with Guzzle. Guzzle itself provides this feature (if you use cURL handler, which is the default).

For example:

$promises = [];
foreach ($data as $value) {
    $promises[] = $guzzleClient->getAsync(/* some URL */);
}

// Combine all promises
$combinedPromise = \GuzzleHttp\Promise\all($promises)

// And wait for them to finish (all requests are executed in parallel)
$responses = $combinedPromise->wait();

If you still want to use Guzzle with ReactPHP event loop, then, unfortunately, there are no straightforward solution. You cat take a look at https://github.com/productsupcom/guzzle-react-bridge (I'm the developer, so feel free to ask questions).