What are some best practices to handle asynchronous responses in PHP when making HTTP requests?

When making asynchronous HTTP requests in PHP, it's important to handle the responses effectively to avoid blocking the execution of other tasks. One common approach is to use libraries like Guzzle that support asynchronous requests with promises or callbacks. By utilizing these features, you can continue executing code while waiting for the response, improving the performance and responsiveness of your application.

use GuzzleHttp\Client;
use GuzzleHttp\Promise;

$client = new Client();

$promises = [
    'response_1' => $client->getAsync('http://example.com/api/endpoint1'),
    'response_2' => $client->getAsync('http://example.com/api/endpoint2'),
];

$results = Promise\settle($promises)->wait();

foreach ($results as $key => $result) {
    if ($result['state'] === 'fulfilled') {
        $response = $result['value'];
        // Process the response data
    } else {
        $exception = $result['reason'];
        // Handle the exception
    }
}