1

使用 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。

4

1 回答 1

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());
}
于 2016-07-14T21:42:46.943 回答