KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I've been reading about the Promise pattern, and I tried to code up a version in PHP with the help of a few examples and my own understanding of how it should work. Is what I came up with a reasonable example of the Promise pattern, or did I implement this incorrectly? 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(); } } } Example use: $promiser->promise(function() { echo "sleeping\n"; sleep(3); return 3; }) ->then(function($args) { echo " in second function, $args\n"; }); $promiser->resolve();
Tags (comma-separated)
Save Edits
Cancel