reactPHP 承诺同步执行

jvr*_*rnt 4 php reactphp

我正在尝试使用 reactPHP 实现类似 js 的承诺。但是由于某些原因方法同步执行,end_at只有在承诺解决后才打印。

代码:

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().


}); 
Run Code Online (Sandbox Code Playgroud)

ema*_*ref 5

承诺本身不是异步的。承诺本身只是让您能够运行一些代码,然后根据成功或失败运行不同的回调,然后将这些概念中的几个链接在一起。

可以使用特定于您的任务的模块来执行异步代码。如果您尝试发出 HTTP 请求,您可以使用ReactPHPhttp-client模块。如果要异步执行系统命令,可以考虑使用child-process模块。

如果您想做一些完全不同或定制的事情,您应该将工作抽象为自己的异步行为,类似于Predis 异步库。也许使用 promise 模块提供成功/失败回调。