php - PHP 应用程序中的 Guzzle 池

标签 php promise guzzle reactphp

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

    $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.

有没有人知道如何让函数等待并获得正确的结果。

最佳答案

如果您可以返回它,那么它在代码风格上就不会是异步的。返回 promise 并在外面打开它。

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 - PHP 应用程序中的 Guzzle 池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28238621/

相关文章:

php - 在没有 SSL/OAuth 的情况下向 Wordpress 提交评论

php - 我的 LOAD DATA INFILE 语法有什么问题?

php - 使用 php 和 mysql 检索注册表单上的电子邮件地址存在困难

javascript - 是否可以从 AngularJS 中 $http.get 的成功方法返回一个值?

Laravel 在 Laravel 之前捕获错误

php - 哪个比较好? iis 上的 php 或 Windows Server 2003(VDS) 上的 WAMP 服务器上的 php

javascript - 使用 Axios 克服 Pending Promise 并在 Node.js 中完成 JSON 构建

javascript - ES6 Promise 错误处理

php - Laravel GuzzleHTTP XML 响应 JSON

php - 将 Postman 请求转换为 guzzle 或其他 PHP HTTP 客户端