How to return response from a go function coroutine

434 Views Asked by At

I'm using the Laravel Swoole Coroutine go function to do a HTTP request in order to achieve better performance. When I get the response from the external service, a new entry is created in the database with the data from the external service.

I want to be able to return a response from the controller with that new DB record. However, it appears that anything outside the go does not have access to anything that got assigned in the go function. I understand that that happens in a separate thread, but is there a way to implement this so that I can have access to the results inside the go function?

Please note that I have coroutine enabled globally and I only to use function as shown below:

public function store(User $user, Request $request) {
   go(function () {
       // get data from external API using Laravel HTTP Client
       ...
       $user = User:create($data);
       return response($user, 201)->send();
   });
}

I have tried using the WaitGroup(), but it complains that the event loop has already been started if I wrap it with the Co\run function.

1

There are 1 best solutions below

0
On
<?
co::run(function() {

    function a($par) {
        $ch = new Chan(1);

        go(function() use ($par, $ch) {
            $res = $par * 2;

            $ch->push($res);
        });

        $ret = $ch->pop();

        return $ret;
    }

    echo '='.a(3);
});