我一直在阅读有关 Promise 模式的内容,并尝试借助一些示例和我自己对它应该如何工作的理解来编写 PHP 版本。我想出了一个合理的 Promise 模式示例,还是我错误地实现了这个?
class PromiseClass {
private $callbacks = array();
private $last_return;
function promise($promise) {
if (get_class($promise) == 'Promise') {
return $promise;
} else if (is_callable($promise)) {
$this->then($promise);
return $this;
}
}
public function then (callable $callback) {
$this->callbacks[] = $callback;
return $this;
}
public function resolve () {
$callback = array_shift($this->callbacks);
if (is_callable($callback)) {
$this->last_return = $callback($this->last_return);
}
if (count($this->callbacks) > 0) {
$this->resolve();
}
}
}
示例使用:
$promiser->promise(function() {
echo "sleeping\n";
sleep(3);
return 3;
})
->then(function($args) {
echo " in second function, $args\n";
});
$promiser->resolve();