phasync
HttpClient / sendAsyncRequest

Method

HttpClient::sendAsyncRequest

Send a PSR-7 request without waiting: the lazy counterpart of HttpClient::sendRequest.

Description#

public HttpClient::sendAsyncRequest(
    RequestInterface $request
): ResponseInterface

Returns a CurlResponse before the transfer has started. The transfer starts when the response's status, headers or body is first read, together with every other request created up to then, so several requests run concurrently without any coroutines in your code. A failure is thrown by that first read, with the same exceptions as sendRequest().

Parameters#

$request RequestInterface

Return values#

ResponseInterface

Examples#

Example 1Send several, read them later
use phasync\HttpClient\HttpClient;
use phasync\Psr\Request;

$base   = require __DIR__ . '/../server.php';
$client = new HttpClient();

$responses = [];
foreach (['one', 'two', 'three'] as $name) {
    $responses[$name] = $client->sendAsyncRequest(Request::create('GET', "$base/slow?seconds=0.1&name=$name"));
}

// The first read starts all three transfers
foreach ($responses as $name => $response) {
    echo "$name: ", $response->getBody(), "\n";
}
Output
one: one
two: two
three: three
Example 2
use phasync\Psr\Request;

$a = $client->sendAsyncRequest(Request::create('GET', 'https://example.com/a'));
$b = $client->sendAsyncRequest(Request::create('GET', 'https://example.com/b'));
echo $a->getStatusCode(), ' ', $b->getStatusCode(); // both transfers run together

See also#