多次請求同一個路由偶爾會出現(xiàn)定位到別的路由接口,比如我請求/user/state接口,偶爾會給我返回/novel/catalogues或者其它接口的內(nèi)容
最近我有在控制器使用如下的自定義函數(shù),希望達(dá)到接口先返回數(shù)據(jù),然后控制器繼續(xù)執(zhí)行不需要返回數(shù)據(jù)的邏輯部分,我猜這么做會造成如上的問題
if (!function_exists('resDefer')) {
function resDefer($response, ?\Closure $callback = NULL) {
if (is_array($response)) $response = \app\struct\Response::build($response);
if (!($response instanceof \app\struct\Response)) {
throw new JsonException(Http::PARAMETER_ERROR_MSG, Http::PARAMETER_ERROR_CODE);
}
$content = Http::json($response->code, $response->message, $response->data);
// 這么做可能有問題
\request()->connection->send($content->withHeaders($response->headers));
if ($callback) $callback();
return $content;
}
}
如題描述
造成這個問題的原因很簡單,因為你一個請求返回了兩次響應(yīng)。
connection->send 發(fā)送了一次響應(yīng) A。
return $content時又發(fā)送了一次響應(yīng) B。
http客戶端都是一次請求獲取一個響應(yīng),客戶端請求第一次拿到響應(yīng)A,下次再請求拿到的大概率是B,所以錯亂。
如果你想異步執(zhí)行個任務(wù),直接定時器就好了。
function resDefer($response, ?\Closure $callback = NULL) {
if (is_array($response)) $response = \app\struct\Response::build($response);
if (!($response instanceof \app\struct\Response)) {
throw new JsonException(Http::PARAMETER_ERROR_MSG, Http::PARAMETER_ERROR_CODE);
}
$content = Http::json($response->code, $response->message, $response->data);
Timer::add(0.000001, $callback, null, false);
return $content;
}