Guzzle pool in PHP application

南楼画角 提交于 2019-12-07 17:03:47

问题


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:


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`
});


来源:https://stackoverflow.com/questions/28238621/guzzle-pool-in-php-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!