How to use await inside a class function?
Parsoolak opened this issue ยท 4 comments
I'm having some difficulty using Block\await
function in reactphp
codes. I implemented this issue in 3 ways but either way it failed to do my task!
Number 1
It will execute correctly but it close the connection and stops server
public function awaitLottieResizer($amount, $asset)
{
try {
$fun = aPromiseFunction(); // it will return PromiseInterface
return await($fun);
} catch (\Exception $e) {
return "Exception";
}
}
Number 2
It won't return anything and code stuck but the server is running
public function awaitLottieResizer($amount, $asset)
{
try {
$fun = aPromiseFunction(); // it will return PromiseInterface
return await($fun, null);
} catch (\Exception $e) {
return "Exception";
}
}
Number 3
It won't return anything and code stuck but the server is running
public function awaitLottieResizer($amount, $asset)
{
try {
$fun = aPromiseFunction(); // it will return PromiseInterface
return await($fun, React\EventLoop\Loop::get());
} catch (\Exception $e) {
return "Exception";
}
}
PS: I use React\Http\HttpServer;
to create my rest api
PROGRESS REPORT:
I Found the issue
When I Call the awaitLottieResizer
function from a promise interface, Ill get the response but when i call it from out of a promise, I Dont Get any response
also when i call it from inside a promise, my inner promise stop and it closed the server
private function processTradesAndApply($balanceArray, $userId): PromiseInterface
{
// Not Work Here
$S = $this->awaitLottieResizer(100, "IRT");
return $this->appManagerDatabase
->createSelectQuery(
"Trades",
['user' => $userId]
)->then(function ($result) use ($balanceArray, $userId) {
// Work Here But Stops the Loop
$S = $this->awaitLottieResizer(100, "IRT");
};
}
a Better Question:
How to wait for promise inside foreach loop in reactphp?
@Parsoolak Thanks for bringing this up! This has been discussed in #20, #44, #49 and others before and this is more or less by design.
As a rule of thumb, mixing blocking and non-blocking code should be avoided. This means these functions should only be used in a blocking application. If you're using a non-blocking application, you should use non-blocking primitives provided by promises and event emitters.
If you're building an HTTP application, here's an example how this can be used with Framework X:
https://gist.github.com/clue/c6f92f48f36ec5061ecf12dde6729a61
I believe this has been answered, so I'm closing this for now. Please come back with more details if this problem persists and we can always reopen this