1

I was playing around with React and wanted to try to get a working timeout function. Following (sort of) the examples and Unit tests from https://github.com/reactphp/promise-timer#timeout I came up with:

use React\Promise\Timer;

$promise = uncertainOperation();
$loop = \React\EventLoop\Factory::create();

Timer\timeout($promise, 1, $loop)->then(
    function ($value) {
        var_dump($value);
    }
    ,
    function ($error) {
        var_dump($error);
    }
);

$loop->run();

function uncertainOperation() {
    return new React\Promise\Promise(
        function ($resolve) {
            for($i = 0; $i < 30000000; $i++) { }
            $resolve("Done");
        }
    );
}

But this always resolves with "Done" no matter how low I set the time in Timer\timeout. What am I missing?

Robse
  • 853
  • 3
  • 14
  • 28

1 Answers1

1

The issue with your code is that it blocks. And it synchronously resolves the promise. It does nowhere return to the event loop driver, so that it could schedule the timeout watcher.

Try changing your code to use a timeout as simulation of e.g. a network timeout.

function uncertainOperation($loop) {
    return new React\Promise\Promise(
        function ($resolve) use ($loop) {
            $loop->addTimer(5, function () {
                $resolve("Done");
            });
        }
    );
}

$loop->run();

Unfortunately, you have to pass around the loop in React.

kelunik
  • 6,750
  • 2
  • 41
  • 70