使用 Guzzle 6,我使用以下代码测试了 Pool/Promise Asynchronous:
$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);
有没有一种方法或重构可以使我不通过引用传递 $values 而是从中接收结果$promise->wait();
?
如中所示: http: //guzzle.readthedocs.io/en/latest/quickstart.html#async-requests
如果我们想忽略所有被拒绝的 Promise 并且等待将返回结果数组中返回的值,有一种方法可以执行 Promise\Settle。