Guzzle pool in PHP application

2019-05-17 18:07发布

I am trying to use Guzzle pool in PHP. But I am having difficulty in dealing with ASYNC request. Below is the code snippet.

    $client = new \GuzzleHttp\Client();

    function test() 
    {
        $client = new \GuzzleHttp\Client();   
        $request = $client->createRequest('GET', 'http://l/?n=0', ['future' => true]);

        $client->send($request)->then(function ($response) {
            //echo 'Got a response! ' . $response;
            return "\n".$response->getBody();
        });

    }
    $res = test();
    var_dump($res); // echoes null - I know why it does so but how to resolve the issue.

Does anybody how can I make function wait and get the correct result.

1条回答
小情绪 Triste *
2楼-- · 2019-05-17 19:12

If you could return it it wouldn't be async in code style. Return the promise and unwrap it on the outside.

function test() 
{
   $client = new \GuzzleHttp\Client();   
   $request = $client->createRequest('GET', 'http://l/?n=0', ['future' => true]);

   // note the return
   return $client->send($request)->then(function ($response) {
       //echo 'Got a response! ' . $response;
       return "\n".$response->getBody();
   });   
}
test()->then(function($body){
     echo $body; // access body here inside `then`
});
查看更多
登录 后发表回答