Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
jot143 opened this issue Nov 29, 2019 · 1 comment
Closed

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

jot143 opened this issue Nov 29, 2019 · 1 comment
Labels

Comments

@jot143
Copy link

jot143 commented Nov 29, 2019

`$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 clue added the question label Nov 29, 2019
@clue
Copy link
Member

clue commented Nov 29, 2019

@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 👍

@clue clue closed this as completed Nov 29, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants