Phillip Whelan
Phillip Whelan

Reputation: 1727

Return synchronously when a React/Promise is resolved

I need to return from a function call once a React/Promise has been resolved. The basic idea is to fake a synchronous call from an ansynchronous one. This means that the outer function must return a value once a promise has been resolved or rejected.

This is to create a driver for RedBeanPHP using React/Mysql. I am aware that this will likely lead to CPU starvation in the React event loop.

My initial idea was to use a generator then call yield inside a \React\Promise\Deferred::then callback.

function synchronous()
{
    $result = asynchronous();
}

function asynchronous()
{
    $deferred = new \React\Promise\Deferred;

    $sleep = function() use ($deferred)
    {
        sleep(5);
        $deferred->resolve(true);
    };

    $deferred->then(function($ret) {
        yield $ret;
    });

    $sleep();
}

The PHP generator class, AFAICT, is only directly constructable by the PHP engine itself. The then callback would need to directly invoke send on the generator of the asynchronous function for this to work.

Upvotes: 1

Views: 2050

Answers (2)

George
George

Reputation: 2950

ReactPhp offers the async tools package which has an await function. Code can then become:

function synchronous()
{
    $result = \React\Async\await(asynchronous());
}

function asynchronous()
{
    $deferred = new \React\Promise\Deferred;

    $sleep = function() use ($deferred)
    {
        sleep(5);
        $deferred->resolve(true);
    };

    $sleep();

    return $deferred->promise();
}

Upvotes: 0

Phillip Whelan
Phillip Whelan

Reputation: 1727

PHP lacks both continuations as well as generator delegation, which would make it possible to call yield from inside a nested callback, making this entirely impossible to achieve for the moment.

Upvotes: 1

Related Questions