Skip to content

Deferred and Promise objects

Greg Bowler edited this page Apr 30, 2025 · 2 revisions

This library separates responsibility between Deferred and Promise objects:

  • The Deferred handles how and when a task runs.
  • The Promise represents the result of that task and is returned immediately.

To integrate this model into a class:

class Example {
	private Deferred $deferred;

	public function doTheTask():Promise {
		$this->deferred = new Deferred(fn() => $this->processFunction());
		return $this->deferred->getPromise();
	}

	private function processFunction():void {
		if($this->isThereMoreWorkToDo()) {
			$this->doMoreWork();
		}
		else {
			$this->deferred->resolve($this->getFinalValue());
		}
	}

	private function isThereMoreWorkToDo():bool { /* ... */ }
	private function doMoreWork():void { /* ... */ }
	private function getFinalValue() { /* ... */ }
}

This can then be consumed like this:

$example = new Example();
$example->doTheTask()
->then(function($finalValue) {
	echo "Final value: ", $finalValue;
});

The caller doesn’t need to know anything about Deferred or Promise; it just uses a public method that returns a PromiseInterface.


Multiple then, catch, and finally functions can be chained together. Learn about how this works in chained promises.

Clone this wiki locally