PHP应用程序中的Guzzle池 [英] Guzzle pool in PHP application

查看:80
本文介绍了PHP应用程序中的Guzzle池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在PHP中使用Guzzle池.但是我在处理ASYNC请求时遇到了困难.下面是代码片段.

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.

推荐答案

如果您可以返回它,它将不会以代码样式异步.退还诺言并在外面解开.

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

这篇关于PHP应用程序中的Guzzle池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆