Search code examples
phpasynchronousguzzlesynchronous

Send Simultaneous HTTP request using guzzle library


I want to send simultaneous request and get data. here is my current code:

 public function getDispenceryforAllPage($dispencery)
    {
        $data = array();
        $promiseGetPagination = $this->client->getAsync($dispencery)
            ->then(function ($response) {
                return $this->getPaginationNumber($response->getBody()->getContents());           
                });
               $Pagination = $promiseGetPagination->wait();


                for ($i=1; $i<=$Pagination; $i++) {

                        $GetAllproducts = $this->client->getAsync($dispencery.'?page='.$i)
                        ->then(function ($response) {

                            $promise =  $this->getData($response->getBody()->getContents()); 
                            return $promise;       
                            });
                            $data[] = $GetAllproducts->wait();  

        }
        return $data; 

    }

I want to get all paginated data of a specific page. Any help would be highly appreciable.


Solution

  • To execute a bunch of promises concurrently, you need of the functions: all(), some(), each() and other from guzzlehttp/promises package.

    Try this one:

    public function getDispenceryforAllPage($dispencery)
    {
        $Pagination = $this->getPaginationNumber(
            $this->client->get($dispencery)->getBody()->getContents()
        );
    
        $GetAllProductPromises = array();
        for ($i = 1; $i <= $Pagination; $i++) {
            $GetAllProductPromises[] = $this->client->getAsync($dispencery . '?page=' . $i)
                ->then(function ($response) {
                    return $this->getData($response->getBody()->getContents());
                });
        }
    
        $data = \GuzzleHttp\Promise\all($GetAllProductPromises);
    
        return $data;
    }