Отправка асинхронных http запросов

Пример кода, который отправляет несколько асинхронных http запросов и обрабатывает результаты когда все ответы получены:

<?php

namespace Drupal\example\DataProvider;

use Drupal\Component\Serialization\Json;
use GuzzleHttp\ClientInterface;
use LogicException;
use function GuzzleHttp\Promise\settle;

/**
 * Receives a data from the API.
 */
class ApiDataProvider {

  /**
   * The HTTP client.
   *
   * @var \GuzzleHttp\Client
   */
  protected $httpClient;

  /**
   * ApiDataProvider constructor.
   *
   * @param \GuzzleHttp\ClientInterface $http_client
   *   The HTTP client.
   */
  public function __construct(ClientInterface $http_client) {
    $this->httpClient = $http_client;
  }

  /**
   * Performs request to the given URLs.
   *
   * @param \Drupal\Core\Url[] $urls
   *   The list of URLs to make request.
   *
   * @return array
   *   An array contains results of each request.
   *
   * @throws \LogicException
   */
  public function request(array $urls): array {
    if (empty($urls)) {
      throw new LogicException('URLs are empty.');
    }

    $responses = $promises = [];

    foreach ($urls as $delta => $url) {
      $promises[$delta] = $this->httpClient->getAsync($url->toString());
    }

    $async_responses = settle($promises)->wait();

    foreach ($urls as $delta => $url) {
      $response = $async_responses[$delta];

      $response_data = [];
      if ($response['state'] === 'rejected' && isset($response['reason'])) {
        /** @var \GuzzleHttp\Exception\ClientException $exception */
        $exception = $response['reason'];

        $response_data = [
          'error_code' => $exception->getCode(),
          'error_message' => $exception->getMessage(),
        ];
      }
      elseif (isset($response['value'])) {
        /** @var \GuzzleHttp\Psr7\Response $response */
        $response = $response['value'];
        $response_data = Json::decode($response->getBody()->getContents());
      }

      $responses[$url->toString()] = $response_data;
    }

    return $responses;
  }

}
Benya