【发布时间】:2018-04-22 19:03:26
【问题描述】:
我有一个缓慢的函数,运行大约需要 20 秒,而 HTTP 请求需要 3.4 秒才能运行。
我想:
- 触发异步 HTTP 请求(应该几乎是 0,因为我不等待响应)
- 然后运行一个慢速函数(~20s)
- 然后在最后得到HTTP请求的结果。 (应该几乎是 0,因为我现在应该已经收到响应,因为 HTTP 请求是异步完成的)
如果 HTTP 请求是异步完成的,那么第 1 步和第 3 步应该几乎可以立即完成。
我使用了以下代码:
$client = new Client();
$promise = $client->getAsync('http://www.fakeresponse.com/api/?sleep=3')->then(
function (ResponseInterface $res) {
return \GuzzleHttp\json_decode($res->getBody()->getContents(), true);
},
function (RequestException $e) {
throw $e;
}
);
// Slow function
$start = microtime(true);
$this->slowFunction(); // ~20s
dump($end);
$start = microtime(true);
$promise->wait();
$end = microtime(true) - $start;
dump($end); // Should be 0 if running async
哪个输出:
19.018649101257
3.3757498264313
这意味着第 3 步运行了大约 3.4 秒,这意味着 ->getAsync 没有触发 HTTP 请求。相反,它会在 ->wait 上触发它。
如何让 HTTP 请求异步触发?
【问题讨论】: