Search code examples
phppromiseguzzlereactphp

Guzzle pool in PHP application


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.


Solution

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