duangu6588 2019-03-05 09:22
浏览 750
已采纳

使用Guzzle池代替guzzle promises

I am using guzzle promises to send a concurrent request but I want to control the concurrency that's why I want to use guzzle pool. How I can transform guzzle promises into guzzle pool. here is my code:

 public function getDispenceryforAllPage($dispencery)
    {
        $GetAllproducts = [];
        $promiseGetPagination = $this->client->getAsync($dispencery)
            ->then(function ($response) {
                return $this->getPaginationNumber($response->getBody()->getContents());           
                });

               $Pagination = $promiseGetPagination->wait();

                $pagearray = array();

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

                        }


                foreach($pagearray as $page_no) {

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

                            $promise =  $this->getData($response->getBody()->getContents()); 
                            return $promise;       
                            });


        }
       $results =  GuzzleHttp\Promise\settle($GetAllproducts)->wait();
        return $results; 
    }
  • 写回答

2条回答 默认 最新

  • duanqian3953 2019-03-06 11:58
    关注

    Just use each_limit() or each_limit_all() (instead of settle()) with a generator.

    function getDispenceryforAllPage($dispencery)
    {
        $promiseGetPagination = $this->client->getAsync($dispencery)
            ->then(function ($response) {
                return $this->getPaginationNumber($response->getBody()->getContents());
            });
    
        $Pagination = $promiseGetPagination->wait();
    
        $pagearray = range(1, $Pagination);
    
        $requestGenerator = function () use ($dispencery, $pagearray) {
            foreach ($pagearray as $page_no) {
                yield $this->client->getAsync($dispencery . '?page=' . $page_no)
                    ->then(function ($response) {
                        return $this->getData($response->getBody()->getContents());
                    });
            }
        };
    
        // Max 5 concurrent requests
        $results = GuzzleHttp\Promise\each_limit_all($requestGenerator(), 5)->wait();
    
        return $results;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制