Guzzle: How to get the response from a pool request

Created on 1 Jul 2015  路  4Comments  路  Source: guzzle/guzzle

Hi,
I am using the latest version of guzzle and attempting to make a pool request. I have succesfully made the request and I can get the responses inside of the closure but, how do I get the response after all the request are done. I cant seem to find documentation on this anywhere. Here is what I have.

 $allBranches =array();

        $requests = function ($projects) {
            foreach($projects as $project){
                yield new Request('GET', "projects/".$project['id']."/repository/branches?per_page=100");
            }
        };

        $pool = new Pool($this->client, $requests($projects), [
            'concurrency' => 5,
            'fulfilled' => function ($response, $index) use ($allBranches) {
               $data = json_decode($response->getBody()->getContents(), true);
                        print_r($data);
                array_push($allBranches,$data);
                //return $data;
            },
            'rejected' => function ($reason, $index) {
                // this is delivered each failed request
                 echo "rejected";
            },
        ]);
        // Initiate the transfers and create a promise
        $promise = $pool->promise();

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

return $allBranches;

with the code above I can see that $data is an array of the response data. but when I push the array in and return it at the end of the function the array is empty.

is there another way to get the response data after the $promise->wait() so that I can return all of the response data?

kinquestion

Most helpful comment

$allBranches is passed by value into your 'fulfilled' closure. You could pass it by reference (e.g., 'fulfilled' => function ($response, $index) use (&$allBranches) { instead.

All 4 comments

$allBranches is passed by value into your 'fulfilled' closure. You could pass it by reference (e.g., 'fulfilled' => function ($response, $index) use (&$allBranches) { instead.

ahh, I feel dumb. Yes that solves my issue. Is this best practice though for what I am trying to do? or is there a better way to get these values from the promise?

There's a static batch method on the Pool class that does something very similar to your example -- it pushes the results of pooled requests onto an array and then returns that array. To use that you would essentially just replace everything from $pool = new Pool(... on down with return Pool::batch($this->client, $requests($projects), ['concurrency' => 5]).

You could also take a look at how to do something similar with $client->getAsync.

Yeah, you can use the batch static method of the Pool class. It's pretty much exactly what you want: https://github.com/guzzle/guzzle/blob/master/src/Pool.php#L94

Was this page helpful?
0 / 5 - 0 ratings