使用Guzzle 6,我用以下代码测试了Pool/Promise异步:
$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-请求
如果我们想忽略所有被拒绝的Promise,并且等待将返回结果数组中返回的值,那么有一种方法可以执行Promise '' Settle。
我不确定你到底想做什么。您需要传递$values
来存储已完成的请求,但不需要通过引用传递。然而,要将所有响应放在一个地方,可以使用Pool
类的静态batch()
方法:
$responses = Pool::batch($client, $requests(10), [
'concurrency' => 5,
'fulfilled' => function ($response, $index) {
},
'rejected' => function ($reason, $index) {
},
]);
然后通过在$responses
:上迭代得到一个Response
类的对象
foreach ($responses as $response) {
var_dump($response->getBody()->getContents());
}