问题描述:

I'm trying to implement js-like promises with reactPHP.

But for some reason methods executed synchronously, the end_at printed only after the promise is resolved.

Code:

function iterate() {

$deferred = new \React\Promise\Deferred();

sleep(2);

$deferred->resolve();

return $deferred->promise();

}

Route::get('test/async', function() {

echo "start execution at ".time()."<br>"; // this executed first

iterate()->then(function($result) {

echo "got result result at ". time() . "<br>"; // this is second

}, function($error) {

}, function ($finally) {

});

echo "end at " . time(); // this is executed only after then().

});

网友答案:

The promise itself is not asynchronous. A promise on its own simply offers you the ability to run some code then a different callback based on success or failure, then chain several of these concepts together.

Asynchronous code can be executed using a module specific to your task. If you're attempting to make an HTTP request, you can use ReactPHP's http-client module. If you want to execute a system command asynchronously, you might consider using the child-process module.

If you're looking to do something entirely different or bespoke, you should abstract the work into its own asynchronous behaviour, similar to the Predis async library. Perhaps using the promise module to provide success/failure callbacks.

相关阅读:
Top