2016-05-17 62 views
1

使用狂飲6,我已經測試泳池/無極異步用下面的代碼:避免通在狂飲6異步參考由池

$client = new \GuzzleHttp\Client(); 
    $urls = []; 
    for($i = 1; $i<10; $i++) { 
     $urls[] = ''https://httpbin.org/get?id='.$i; 
    }  

    $requests = function ($urls){ 
     if(!empty($urls)) { 
      foreach($urls as $uri){ 
       yield new \GuzzleHttp\Psr7\Request('GET', $uri); 
      } 
     } 
    }; 
    $values = []; 
    $pool = new \GuzzleHttp\Pool($client, $requests($urls), [ 
     'concurrency' => 5, 
     'fulfilled' => function ($response, $index) use (&$values){ 
      // this is delivered each successful response 
      return $values[]=$response->getStatusCode(); 
     }, 
     'rejected' => function ($reason, $index){ 
      // this is delivered each failed request 
      //dd($reason); 
      return $reason->getResponse(); 
     }, 
    ]); 

// Initiate the transfers and create a promise 
    $promise = $pool->promise(); 

// Force the pool of requests to complete. 
    $promise->wait(); 
    var_dump($values); 

有沒有一種方法或重構,使我不通過參考$值,而不是從$promise->wait();接收結果?

曾經出現在:http://guzzle.readthedocs.io/en/latest/quickstart.html#async-requests

有辦法做到無極\結算,如果我們想忽略所有被拒絕的承諾,並等待返回的結果數組中返回的值。

+0

你爲什麼應該通過'$價值'參考在第一個地方? – revo

+0

@revo爲了得到響應,因爲函數將promise返回到$ pool。 – azngunit81

回答

1

我不確定你想要做什麼。您需要通過$values來存儲滿足的請求,但不需要通過引用來傳遞它。但是有一個地方的所有響應,你可以使用靜態batch()方法Pool類:

$responses = Pool::batch($client, $requests(10), [ 
    'concurrency' => 5, 
    'fulfilled' => function ($response, $index) { 
    }, 
    'rejected' => function ($reason, $index) { 
    }, 
]); 

然後,通過迭代有Response類的一個對象在$responses

foreach ($responses as $response) { 
    var_dump($response->getBody()->getContents()); 
}