Php 同步执行
我试图用PHP实现类似js的承诺。 但由于某些原因,同步执行的方法只有在承诺得到解决后才会打印处的Php 同步执行,php,reactphp,Php,Reactphp,我试图用PHP实现类似js的承诺。 但由于某些原因,同步执行的方法只有在承诺得到解决后才会打印处的end\u 代码: 函数迭代(){ $deferred=new\React\Promise\deferred(); 睡眠(2); $deferred->resolve(); 返回$deferred->promise(); } 路由::get('test/async',function()){ echo“在“.time().”“”;//首先执行此命令 迭代()->then(函数($result){ e
end\u
代码:
函数迭代(){
$deferred=new\React\Promise\deferred();
睡眠(2);
$deferred->resolve();
返回$deferred->promise();
}
路由::get('test/async',function()){
echo“在“.time().”“
”;//首先执行此命令
迭代()->then(函数($result){
echo“在“.time().”“
”;//这是第二个
},函数($error){
},函数($finally){
});
echo“end at”.time();//这只在then()之后执行。
});
承诺本身不是异步的。承诺本身只是让您能够运行一些代码,然后根据成功或失败运行不同的回调,然后将这些概念链接在一起
异步代码可以使用特定于任务的模块执行。如果您试图发出HTTP请求,可以使用的模块。如果你想异步执行系统命令,你可以考虑使用这个模块。
如果您希望做一些完全不同或定制的事情,那么您应该将工作抽象为它自己的异步行为,类似于。可能使用promise模块提供成功/失败回调。代码中的问题是使用了阻塞函数:sleep()
以下列举了一些阻止调用:
但是promise本身是异步的:它提供了在调用函数之前声明要在链中调用的函数的能力
事实上,通过调用一个函数,您必须等到该函数被执行,但声明“那么您必须运行它”,第一次调用返回时,您并不是在真正运行它
所以
函数迭代(){
全球美元循环;
$deferred=new\React\Promise\deferred();
$loop->addTimer(2,函数()使用($deferred){
$deferred->resolve();
});
返回$deferred->promise();
}
路由::get('test/async',function()){
echo“在“.time().”“
”;//首先执行此命令
迭代()->then(函数($result){
echo“在“.time()”
“;//解决此问题时得到结果”
},函数($error){
},函数($finally){
});
echo“end at”.time();//这仅在iterate()之后执行,然后()返回。
});
我假设您有一个全局$loop=React\EventLoop\Factory::create()代码>,大多数情况下它是有意义的
这里$loop->addTimer()
立即调用return,因此iterate()
返回未解决的承诺,因此立即调用方法then()
,然后继续执行,echo end在…
then()
方法将行为附加到返回的承诺,不执行作为参数传递的函数。但首先必须返回承诺,问题是睡眠不是异步睡眠,但它实际上可以睡眠2秒钟
请注意,在javascript中,您没有对应的睡眠,您有setTimeout()
,其行为与此类似$loop->addTimer()
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().
});
function iterate() {
global $loop;
$deferred = new \React\Promise\Deferred();
$loop->addTimer(2, function () use ($deferred) {
$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 when solved
}, function($error) {
}, function ($finally) {
});
echo "end at " . time(); // this is executed only after iterate() and then() returns.
});