发送Guzzle的“异步”请求,而无需调用“等待”

时间:2019-05-15 09:19:21

标签: php asynchronous guzzle

我正在尝试向端点发送请求,但是我不想等待它们响应,因为我不需要响应。所以我正在使用Guzzle,方法如下:

$url = 'http://example.com';

$client = new \Guzzelhttp\Client();
$promise = $client->postAsync($url, [
    'headers' => ['Some headers and authorization'],
    'query' => [
        'params' => 'params',
    ]
])->then(function ($result) {
    // I don't need the result. So I just leave it here.
});

$promise->wait();

我知道,我必须在wait上调用client方法,才能实际发送请求。但这完全否定了请求是“异步”的,因为如果无法访问该URL或服务器已关闭,则该应用程序将等待超时或任何其他错误。

所以,这里的问题是,当您必须等待响应时,Guzzle的“异步”是什么意思?以及如何使用PHP调用真正的异步请求?

谢谢

3 个答案:

答案 0 :(得分:1)

如果不想等待结果,请调用then()方法:

$client = new GuzzleClient();
$promise = $client->getAsync($url)
$promise->then();

then()调用将发出HTTP请求而无需等待结果,非常类似于

curl_setopt(CURLOPT_RETURNTRANSFER,false) 

答案 1 :(得分:0)

您可以做的是:

    $url = 'http://example.com';

    $client = new \Guzzelhttp\Client();
    $promise = $client->postAsync($url, [
        'headers' => ['Some headers and authorization'],
        'query' => [
            'params' => 'params',
        ]
    ])->then(function ($result) {
         return $result->getStatusCode();
    })
->wait();

echo $promise;

您需要将wait()作为最后一行被调​​用,以便获得来自您的诺言的结果。

在这种情况下,它将仅返回状态码。

就像在Github中提到的那样,我无法“解雇”,所以我认为您想要实现的目标,例如像Vue或React这样的完整承诺,在这里对您不起作用。

另一种方法以及我个人所做的是在耗时请求中使用try-catch,因此,如果出现耗时错误,则可以捕获并引发异常。

答案 2 :(得分:0)

use Illuminate\Support\Facades\Http;


...Some Code here

$prom = Http::timeout(1)->async()->post($URL_STRING, $ARRAY_DATA)->wait();

... Some more important code here

return "Request sent"; //OR whatever you need to return

这对我有用,因为我不需要总是知道响应。 它仍然使用 wait(),但由于超时值很小,它不会真正等待响应。

希望这对其他人有帮助。