简体   繁体   中英

Async in Laravel 5.4 with Dingo API

I want my APIS made with DINGO can run ASYNC. Currently, my api is sync because when i try to request an API with sleep command and then I call another api, the second api just return value when firt request is passed over the sleep time. This is the code I used to test:

First api route:

 public function checkLongRunning(Request $request){
        $data = $request->all();
        if($data['check'] == 1){
           sleep(5);
            return response()->json(['error' => 'slept in 5 secs'], 500);
        }else{
            return response()->json(['error' => 'bad request'], 500);
        }
    }

Second api route:

public function checkLongRunning2(Request $request){
        $data = $request->all();
        if($data['check'] == 1){
            return response()->json(['error' => 'OK'], 500);
        }else{
            return response()->json(['error' => 'asd'], 500);
        }
    }

Is there anyway I can make my API (build with DINGO in Laravel 5.4) run ASYNC (can request another api when first api request are sleeping)?

Thank you.

You can response the request immediately after you've done everything you need (Auth, etc.), and you need a middleware attach to the endpoint so you can run the code after response been returned.

Example:

In api.php

$api->post('run', function () {
                        return response()->json([
                            "message" => "running"
                        ], 200);
                    })->middleware("postRun");

In "postRun" middleware

public function terminate($request, $response)
{
    sleep(2000) // place your code here.
}

BTW: You'll need to register the middleware.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM