public requestAsync ( $method, $uri = '', array $options = [] ) | ||
$options | array |
use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; $client = new Client(); $promises = []; // set up five Guzzle client requests asynchronously for ($i = 1; $i <= 5; $i++) { $promises['req_' . $i] = $client->requestAsync('GET', 'https://jsonplaceholder.typicode.com/todos/' . $i); } // wait for all requests to complete $results = GuzzleHttp\Promise\all($promises)->wait(); // output the response status codes foreach ($results as $key => $response) { echo "$key - " . $response->getStatusCode() . "\n"; }
use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; $client = new Client(); $urls = [ 'https://jsonplaceholder.typicode.com/todos/1', 'https://jsonplaceholder.typicode.com/todos/2', 'https://jsonplaceholder.typicode.com/todos/3', ]; // set up multiple Guzzle client requests asynchronously foreach ($urls as $url) { $promises[] = $client->requestAsync('GET', $url); } // output the response data foreach (GuzzleHttp\Promise\settle($promises)->wait() as $response) { if ($response['state'] === 'fulfilled') { echo $response['value']->getBody(); } else { echo $response['reason']->getMessage(); } }In this example, we set up multiple asynchronous Guzzle client requests based on an array of URL addresses. We store each request as a promise in a flat array. Then we use the GuzzleHttp\Promise\settle method to wait for the first promise to be resolved, and finally output the response data if the promise is fulfilled, or an error message if it is rejected. Both examples use the GuzzleHttp client library, which is a popular HTTP client for PHP. It provides a simple interface for sending HTTP requests and handling responses.