使用枪口库发送同时HTTP请求

时间:2019-03-04 09:58:06

标签: php asynchronous guzzle synchronous

我想同时发送请求并获取数据。这是我当前的代码:

 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; 

    }

我想获取特定页面的所有分页数据。任何帮助都是非常可取的。

1 个答案:

答案 0 :(得分:0)

要同时执行一堆承诺,您需要使用guzzlehttp / promises包中的函数all(),some(),eacher()和其他函数。

尝试这个:

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;
}