reactphp / promise

Promises/A implementation for PHP.
https://reactphp.org/promise/
MIT License
2.38k stars 146 forks source link

Is there is any way in Reactphp to run code really asynchronously #152

Closed jot143 closed 4 years ago

jot143 commented 4 years ago

`$one = function() { sleep(5); echo "one"; };

$two = function() { sleep(5); echo "two"; };

$three = function() { sleep(5); echo "three"; }; $loop = \React\EventLoop\Factory::create();

$loop->addTimer(1,function() use($one) { $one(); });

$loop->addTimer(1,function() use($two) { $two(); });

$loop->addTimer(1,function() use($three) { $three(); });

$loop->run();`

As in JavaScript i get result after 5 sec > "onetwothree" but here it behave as normal php, get result after 15sec. so what i the benefit of this react.

///////////////////////////

Let Suppose i have three query to mysql; Q1, Q2, Q3

can in React these run in parallel ? if these run like Q1 then Q2 and then Q3, so why we use React.

clue commented 4 years ago

@jot143 Hi and welcome to @ReactPHP!

Promises don't make synchronous code magically asynchronous (#120 and others). In fact, your code snippet does not even use promises.

It looks like you may not want to "sleep" (i.e. "pause" the execution of the program) but rather "await" a timer to fire. In this case, you can directly use the loop and adjust your timer numbers accordingly in your previous example or use the React\Promise\Timer\resolve() function like this:

Timer\resolve(1.5, $loop)->then(function ($time) {
    echo 'Thanks for waiting ' . $time . ' seconds' . PHP_EOL;
});

See https://github.com/reactphp/promise-timer#resolve for details.

I hope this helps :+1: