我在Promise
中创建JavaScript
,我决定使用线程。所以,我有以下课程:
class Promise extends Thread {
protected $action = null;
protected $then = null;
protected $catch = null;
public function __construct(callable $callback){
$this->action = $callback;
$this->start();
}
public function run(){
call_user_func_array($this->action, [
function($result){
if($this->then !== null){
call_user_func($this->then, $result);
}
},
function($result){
if($this->catch !== null){
call_user_func($this->catch, $result);
}
}
]);
}
public function then(callable $callback){
$this->then = $callback;
return $this;
}
public function catch(callable $callback){
$this->catch = $callback;
return $this;
}
}
然后我运行以下代码来测试它:
// Run the first thread
(new Promise(function($resolve, $reject){
sleep(5);
$resolve(true);
}))->then(function(){
echo 'Resolved 5 second promise' . PHP_EOL;
});
// Run the second thread
(new Promise(function($resolve, $reject){
sleep(2);
$resolve(true);
}))->then(function($result){
echo 'Resolved 2 second promise' . PHP_EOL;
});
// Show a status
echo 'Waiting for Promises\' to complete' . PHP_EOL;
运行时,我期待以下输出:
等待承诺'完成
解决了2秒承诺 解决了5秒承诺
我得到以下输出:
解决了5秒承诺 解决了2秒承诺 等待Promises'完成
那么,为什么它不像时尚一样在线程中运行呢?
我注意到,如果我将Promise
分配给变量,它会正确输出,但我觉得我不应该这样做......