dsl2014 2019-05-15 09:19
浏览 495

发送Guzzle的“异步”请求而不调用“等待”

I'm trying to send a request to an endpoint, but I don't want to wait for them to respond, as I don't need the response. So I'm using Guzzle, here's how:

$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();

A I understood, I have to call the wait method on the client in order to actually send the request. But it's totally negates the request being "async" because if the url was not accessible or the server was down, the application would wait for a timeout or any other errors.

So, the question here is, what does Guzzle mean by "async" when you have to wait for the response anyway? And how can I call a truly async request with PHP?

Thanks

  • 写回答

1条回答 默认 最新

  • dongxia4880 2019-05-15 09:35
    关注

    What you can do is:

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

    You need the wait() to be called as the last line so you get the result which will come from your promise.

    In this case it will return just the status code.

    Just as mentioned in Github is not able to "fire and forget"so i think what you are trying to achieve, like a complete promise like in Vue or React won't work for you here the way you want it to work.

    Another approach and what i do personally is to use a try-catch on guzzle requests, so if there is a guzzle error then you catch it and throw an exception.

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大