I am making a Promise
like in JavaScript
, and I decided to do it using threads. So, I have the following class:
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;
}
}
I then run the following code to test it:
// 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;
When running this, I was expecting the following output:
Waiting for Promises' to complete
Resolved 2 second promise
Resolved 5 second promise
I instead get the following output:
Resolved 5 second promise
Resolved 2 second promise
Waiting for Promises' to complete
So, why is it not running in a thread like fashion?
Edit
I noticed that if I assign the Promise
to a variable it outputs correctly, but feel I shouldn't have to do that...
Aucun commentaire:
Enregistrer un commentaire