Skip to content

Getting started

Greg Bowler edited this page May 4, 2026 · 1 revision

Before we can use this package, we need to install it with Composer and create a Deferred that exposes a Promise.

Install with Composer

composer require phpgt/promise

A first standalone example

The smallest useful setup is:

use GT\Promise\Deferred;

$deferred = new Deferred(function() use (&$deferred) {
	$deferred->resolve("Finished");
});

$promise = $deferred->getPromise();
$promise->then(function(string $message) {
	echo $message, PHP_EOL;
});

foreach($deferred->getProcessList() as $process) {
	$process();
}

Here is what happens:

  1. We construct a Deferred.
  2. The Deferred creates and keeps a matching Promise.
  3. We attach a then() callback to the promise.
  4. We run the deferred process callback.
  5. The process resolves the promise, so the then() callback runs.
  • Deferred and Promise are separate objects with separate jobs.
  • The package does not run process callbacks for us.
  • then(), catch(), and finally() can be attached before or after resolution.
  • A promise stays pending until something calls resolve() or reject().

If you are coming from JavaScript, the syntax will look familiar, but the scheduling is more explicit because PHP does not provide an event loop by default.


Next, learn the difference between Deferred and Promise objects.

Clone this wiki locally