-
-
Notifications
You must be signed in to change notification settings - Fork 2
Home
In computer science, a Promise is a construct that bridges the gap between procedural code and asynchronous execution. In procedural languages like PHP, functions influence program flow by either returning a value or throwing an exception, but when dealing with asynchronous operations, we can't return a value (because it isn't ready yet), and we can't throw an exception (because there's no clear place to catch it).
This is where Promises come in. Instead of returning a value or throwing an exception, an asynchronous function returns a Promise: an object that will eventually be settled by fulfilling with a value or rejecting with an error — but not immediately.
In this library, that background work is encapsulated by the Deferred class, which allows execution to be deferred while still exposing a Promise object that can be resolved or rejected later.
This implementation follows the [Web API's Promise specification][mdn-promise] in terms of syntax and expected behaviour — using then, catch, and finally — but is tailored to work natively in PHP.
Note
While the API is compatible with Promises/A+, this library differs in one important way: instead of returning a new Promise with each then, catch, or finally call, it maintains and returns the same instance throughout the chain. This design keeps memory usage lower, avoids deep call stacks, and results in simpler, more predictable code — especially helpful in procedural environments like PHP.
- Exposes
PromiseInterfacewiththen(),catch(),finally(), andgetState(). - Exposes
DeferredInterfacefor managing asynchronous work and resolving the related promise. - Supports chaining by returning scalar values,
null, or anotherPromiseInterfacefrom callbacks. - Uses PHP parameter types to decide which chained callback should run.
- Leaves scheduling to your own loop, or to a separate package such as PHP.GT/Async.
Note
This package is fully usable on its own for implementing Promise-driven libraries. The examples in this guide are standalone PHP examples. Framework-specific usage in PHP.GT/WebEngine is documented separately in the WebEngine docs.
use GT\Promise\Deferred;
$deferred = new Deferred();
$promise = $deferred->getPromise();
$promise->then(function(string $message) {
echo $message, PHP_EOL;
});
$deferred->resolve("Task complete");This example resolves immediately, so it does not need a loop yet. Real asynchronous work is usually spread across repeated process callbacks, which we will look at next.
Start with Getting started to install the package and build a minimal deferred task.
PHP.GT/Promise is a separately maintained component of PHP.GT/WebEngine.