prooph / service-bus

PHP Lightweight Message Bus supporting CQRS.
http://getprooph.org
BSD 3-Clause "New" or "Revised" License
441 stars 55 forks source link

How to deal with promises #145

Closed dropdevcoding closed 7 years ago

dropdevcoding commented 7 years ago

Hello, since I'm implementing an application using ES/CQRS (completely using Prooph components), I'm wondering how to deal with the following situation:

  1. I'm sending a GET request to the server (NOT react PHP) and I want to return a result from my read model using the QueryBus
  2. The QueryBus works asynchronously which is perfect since the read model could be stored anywhere
  3. My Finder returns the promise
  4. Now, since I'm on a blocking server using a regular webframework my action wants me to return a value directly (synchronously)

So, how to deal with it?

public function myAction($request) {
    $query = MyQuery::with($request->getTheParam());
    $promise = $this->queryBus->dispatch($query);
    $result = null;
    $promise->then(function ($queryResult) use (&$result) {
       $result = $queryResult;
   });

  return new ActionResult($result);
}

This approach works since the query happens within the request on the same server accessing the DB and blocks but it won't work anymore when moving my read model to any other async service because the action would return without waiting for the promise to be finished (of course).

In addition my current solution above feels really clumsy imho. I'm I missing something / getting something wrong?

Guzzle Promises support $promise->wait() which would be a solution for this case I think.

Thank you in advance!

codeliner commented 7 years ago

Hi, we just return a reactPHP promise to allow you to execute queries async and continue with other stuff while you are waiting for the response. How to deal with it is userland implementation ;) Maybe you can get some ideas from this post: http://stephencoakley.com/2015/06/11/integrating-guzzle-6-asynchronous-requests-with-reactphp

Let me know if it helps you!

dropdevcoding commented 7 years ago

Looks promising ;-)

Also I realized that you are using the approach I mentioned above as well in your PSR-7 middleware what already soothed me sufficiently.

Thank you very much!