Alex Boroda
Alex Boroda

Reputation: 11

ReactPHP and Promises

I'm trying to understand the concept of Promises using ReactPHP

$app = function ($request, $response) use ($redis, $config) {

    $promise = React\Promise\all(
        array(
            AsyncGetUser(),
            AsyncGetDB(),
            AsyncGetTemplate()
        )
    )->then(function ($res) {
        $result = ParseTemplate($user, $template, $whatever);
    }

    \React\Promise\resolve($promise);


    $response->writeHead(200, array('Content-Type' => 'text/plain'));
    $response->end($result);

}

$http->on('request', $app);

But $response is sent before $result is ready. How can do something like await for $promise so I send $result properly ?

I've tried to move $response->end to another->then() section but then I don't get any response in browser (i.e. the script gets a result when $app = function is finished already).

Upvotes: 1

Views: 777

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

I don't know reactphp at all, but if promises work like promises in JS for example, seems like you need to write the response in the ->then where you have a result!

$app = function ($request, $response) use ($redis, $config) {
    $promise = React\Promise\all(
        array(
            AsyncGetUser(),
            AsyncGetDB(),
            AsyncGetTemplate()
        )
    )->then(function ($res) {
        $result = ParseTemplate($user, $template, $whatever);
        $response->writeHead(200, array('Content-Type' => 'text/plain'));
        $response->end($result);
    }
}

$http->on('request', $app);

Note: the following line in your code

\React\Promise\resolve($promise);

makes no sense. \React\Promise\resolve doesn't "resolve the promise" as you seem to think, it creates and returns a resolved promise - which you discard!

Upvotes: 1

Related Questions