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

发送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.

    评论

报告相同问题?

悬赏问题

  • ¥100 c语言,请帮蒟蒻看一个题
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)