我正在重写与API端点通信并在最终确定后收到最终响应的旧服务,他们称之为异步。
所以我的原始脚本使用了以下简化逻辑:
$response = $this->myCustomCurlResponseProcessor();
if ($response['state'] === 'started') {
sleep(3);
}
$repeats = 0;
do {
$response = $this->myCustomCurlResponseProcessor();
if ($response['state'] === 'in_progress') {
sleep(3);
}
$repeats++;
} while ($response['state'] === 'in_progress' && $repeats < 30);
if ($response['state'] !== 'finished') {
throw new \RuntimeException('Failed to process request');
}
// process response
我很好奇是否可以通过异步请求处理此逻辑并重试中间件,例如:
$promise = $client->requestAsync('GET', 'data', [
'query' => [
//my params
]
]);
$promise->then(
static function (ResponseInterface $res) {
// handle only responses with state "finished"
// other states like started, in_progress, failed should be handled elsewhere
},
static function (RequestException $e) {
//handle error response
}
);
$promise->wait();