PHP Luminova: Work with Promises
Create, chain, and combine Luminova promises. Handle fulfillment, rejection, and cancellation, or adapt a callback-based task to return a promise.
A promise represents an operation in one of three states. A pending promise can be fulfilled with a value or rejected with a reason. Attach a handler with then() for success, catch() for rejection, or canceled() for explicit cancellation. Use error() to handle misuse of the promise API, such as settling a promise twice.
Use Deferred when another part of the application will settle the promise. Use Fulfilled or Rejected when the outcome is already known.
Catch vs Error
- Use
catch()to handle a rejected operation, such as a failed request or invalid input. - Use
error()to handle errors reported by the promise itself, such as an attempt to settle it twice.
Promise Initialization Examples
Executor-Style Promises
An executor runs when the promise is created and receives the callbacks that fulfill or reject it. Declaring both parameters as callable makes their role clear.
use Luminova\Promise\Promise;
// Recommended: fully type-hinted
$p = new Promise(function (callable $resolve, callable $reject): void {
$resolve('Success');
// or
// $reject(new Exception('Failed'));
});
// Still valid without type-hinting
$p = new Promise(function ($resolve, $reject): void {
$resolve('Success');
});With only a resolver
Declare the single parameter as callable so the constructor treats it as a settlement callback.
$p = new Promise(function (callable $resolve): void {
$resolve('Success');
});Untyped single parameter
The constructor registers this callback as a fulfillment handler and leaves the promise pending.
$p = new Promise(function ($resolve): void {
$resolve('Value'); // Silently fails
});Direct Handlers
Direct handlers receive the fulfillment value or rejection reason after your code settles the promise.
$p = new Promise(function (mixed $value): void {
echo "Resolved value: $value";
});
// With resolved and rejection handlers
$p = new Promise(
function (mixed $value) {
echo "Resolved: $value";
},
function (Throwable $reason) {
echo "Rejected: " . $reason->getMessage();
}
);Common Initialization Mistakes
An executor that returns without calling a settlement callback leaves the promise pending. A later call to resolve() or reject() can still settle it. Once settled, a second attempt is a promise operation error.
$p = new Promise(
function (callable $value, callable $reject) {
// Wrong: cannot resolve properly here
},
function (Throwable $reason) {
// Access rejected reason
}
);
// Attempting to resolve/reject manually fails
$p->resolve('Bad'); // Nothing happens
$p->reject('Bad'); // Nothing happens
$p->then(function ($val) {
// Callback will not be executed
});Usage Examples
These examples show how to chain operations, handle failures, and read a result.
Key Points:
- Type a single executor parameter as
callable. With two executor parameters, type hints are optional.then()can return a newPromisefor chaining operations.- Use
catch()for rejections andfinally()for cleanup after fulfillment or rejection.
Nested Chains
A then() handler can return another promise. The next handler in this example receives the value from the inner promise.
use Luminova\Promise\Promise;
$promise = new Promise(fn(callable $resolve) => $resolve('start'));
$promise->then(function ($val): PromiseInterface {
echo "First: $val\n";
return new Promise(fn(callable $resolve) => $resolve('end'));
})->then(function (string $val) {
echo "Second: $val\n";
});
// Output:
// First: start
// Second: endAsynchronous Operations
The executor below simulates an operation that can succeed or fail. For an external callback that runs after the executor returns, use Deferred.
use Luminova\Promise\Promise;
$promise = new Promise(function (callable $resolve, callable $reject): void {
$data = rand(1, 10);
if ($data > 5) {
$resolve("Success with data: $data");
} else {
$reject(new \Exception("Failure with data: $data"));
}
});
$promise->then(function (string $result) {
return "First Result: {$result}\n";
})
->then(function (string $value) {
echo "Next Result: " . $value;
})
->catch(function (\Throwable $error) {
echo "Error: " . $error->getMessage() . PHP_EOL;
})
->finally(function() {
echo "All done" . PHP_EOL;
});Handling Resolved and Rejected States
Register direct handlers for both outcomes, then call resolve() with a value or reject() with a reason.
use Luminova\Promise\Promise;
$promise = new Promise(
function (mixed $value) {
echo "Hello " . $value;
},
function (\Throwable $reason) {
echo "Rejected with reason: " . $reason->getMessage();
}
);
// Resolve the promise directly
$promise->resolve('World!');
// Output: Hello WorldNote: You can also reject directly using
$promise->reject(new \Exception('Reason')).
Error Propagation
Throw an exception from a fulfillment handler to reject the next promise. A rejection handler can report that exception or throw another one with more context.
use Luminova\Promise\Promise;
$promise = new Promise();
$promise
->then(function (int $value) {
throw new \Exception((string) ($value + 1));
})
->catch(function (\Throwable $e) {
// Re-throw to propagate rejection
throw $e;
})
->catch(function (\Throwable $e) {
// Optionally transform or propagate
throw new \Exception($e->getMessage() + 1);
})
->catch(function (\Throwable $e) {
echo 'Final Reject: ' . $e->getMessage();
// Output: Final Reject: 3
});
// Start the chain
$promise->resolve(1);When each rejection handler needs to produce a separate step in the chain, use
then(null, $onRejected).
Third-Party Promises
A fulfillment handler can return a Luminova promise or a compatible object that exposes then(). The examples illustrate returning a promise from a handler and forwarding callbacks from an external library. Replace the placeholder classes with the APIs your project uses.
Examples:
$promise->then(function (string $result) {
// Return a new promise object
$p = new \Some\ThirdParty\Promise();
$p->resolve('ThirdParty Promise Resolved With: ' . $result);
// Alternatively, return a new Luminova promise
// return new Luminova\Promise\Fulfilled('Resolved for: ' . $result);
// Or return a rejected promise
// return new Luminova\Promise\Rejected(new \Error('Rejected for: ' . $result));
return $p;
})->then(function (Luminova\Interface\PromiseInterface $p) {
// Decide to return the promise object
return $p;
// Or handle it directly here
// $p->then(function ($value) {
// echo $value;
// })->catch(function (\Throwable $error) {
// echo "Error: " . $error->getMessage();
// });
})->then(function (string $value) {
// If decided to return the promise object in above then
// Handle the resolved value here
echo $value;
})->catch(function (\Throwable $error) {
echo "Error: " . $error->getMessage();
});
// Resolve the original promise
$promise->resolve('https://example.com');Wrapping a third-party promise
Forward the external result or rejection to the matching Luminova settlement callback. Use a Deferred if the external library invokes its callbacks after the executor returns.
$promise = new Promise(function (callable $resolve, callable $reject) {
Foo\Bar\Async::promise()
->then(fn($value) => $resolve($value)) // Resolve the value with Luminova promise
->otherwise(fn(mixed $error) => $reject(
($error instanceof Throwable) ? $error : new \Exception($error)
)); // Reject with a Throwable or a generic exception
});
// Using Luminova's chaining methods for the promise
$promise->then(function ($value) {
echo "Resolved Value: " . $value;
})
->error(function (Throwable $e) {
echo "Error: " . $e->getMessage();
});Wait Until Fulfillment or Rejection
Call wait() on the final promise to read the result of the chain.
$promise = new Promise();
$wait = $promise
->then(fn(int $value): int => $value * 2) // Transforms 10 → 20
->then(fn(int $value): int => $value + 5); // Transforms 20 → 25
$promise->resolve(10);
echo $wait->wait(); // Outputs: 25Note: A pending promise with no queued handlers can return
nullimmediately. Arrange for external work to complete before assuming a result is available.
Handling Mixed Values and Exceptions
A chain can process ordinary values and exceptions. Use catch() to handle a rejection and attach finally() where cleanup should run.
$promise = new Promise();
$promise
->then(fn(int $value): int => $value + 1) // 1 → 2
->then(fn(int $value) => throw new \Exception($value + 1)) // Throws 3
->catch(fn(\Throwable $e) => $e->getMessage() + 1) // 3 + 1 → 4
->finally(fn($value) => print('Total ' . $value)); // Outputs: Total 4
$promise->resolve(1);Note: The
finally()callback receives the value or rejection reason of the promise it is attached to.
Sequential Value Resolution
Each then() handler receives the preceding result. Return the transformed value to pass it to the next step.
$promise = new Promise();
$promise
->then(fn(int $x): int => $x + 1) // 1 → 2
->then(fn(int $x): int => $x + 1) // 2 → 3
->then(fn(int $x): int => $x + 1) // 3 → 4
->then(fn(int $x) => print('Resolved: ' . $x)); // Outputs: Resolved: 4
$promise->resolve(1); // Starts the chain with value 1Advanced Handling
This example uses a random input to select fulfillment, rejection, cancellation, or a second settlement attempt. To observe cancellation, register canceled() on the same promise you call cancel() on.
use Luminova\Promise\Promise;
// Create a promise and define a logic error handler
$promise = (new Promise())->error(function (\Throwable $e) {
echo 'Logic Error: ' . $e->getMessage() . PHP_EOL;
});
// Chain multiple handlers for fulfillment, rejection, and cancellation
$chain = $promise
->then(function ($value) {
echo "Resolved with value: {$value}" . PHP_EOL;
})
->catch(function (\Throwable $e) {
echo "Error: {$e->getMessage()}" . PHP_EOL;
})
->canceled(function ($reason, string $state) {
echo "Canceled with reason: {$reason}, in state: {$state}" . PHP_EOL;
});
// Simulate dynamic data to trigger different promise states
$data = rand(0, 15);
if ($data >= 5 && $data < 10) {
// Fulfill the promise
$promise->resolve("Value: {$data}");
} elseif ($data === 0) {
// Logic error: attempt both resolve and reject
$promise->resolve("Resolve Value: {$data}");
$promise->reject("Rejected: {$data}");
} elseif ($data < 5) {
// Reject the promise
$promise->reject("Rejected: {$data}");
} else {
// Cancel the promise
$chain->cancel("Canceled: {$data}");
}Class Definition
- Full namespace:
Luminova\Promise\Promise - This class implements Luminova\Interface\PromiseInterface.
- This class is final.
Constants
| Constant | Value |
|---|---|
PENDING | 'pending' |
FULFILLED | 'fulfilled' |
REJECTED | 'rejected' |
Methods
__construct
Create a pending promise. An executor receives settlement callbacks. A callback with a single value parameter can instead register a fulfillment handler. A callback with no parameters runs immediately and leaves the promise pending.
public function __construct(?callable $onResolved = null, ?callable $onRejected = null)Parameters:
| Parameter | Type | Description |
|---|---|---|
$onResolved | ?callable | Executor or fulfillment handler. Defaults to null. |
$onRejected | ?callable | Rejection callback. Defaults to null. |
then
Register fulfillment and rejection handlers and obtain the next promise in the chain.
public function then(?callable $onResolved = null, ?callable $onRejected = null): PromiseInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$onResolved | ?callable | Fulfillment callback. Defaults to null. |
$onRejected | ?callable | Rejection callback. Defaults to null. |
Return:
PromiseInterface - The resulting promise.
catch
Register a rejection handler on this promise.
public function catch(callable $onCatch): PromiseInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$onCatch | callable | Callback that receives the rejection reason. |
Return:
PromiseInterface - The current promise.
finally
Run a callback for either settlement outcome. Its result is used in the resulting promise.
public function finally(callable $onFinally): PromiseInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$onFinally | callable | Callback that receives the settled value or reason. |
Return:
PromiseInterface - The resulting promise.
canceled
Register a callback for explicit cancellation.
public function canceled(callable $onCancelled): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$onCancelled | callable | Callback that receives the cancellation reason and state. |
Return:
self - The current promise.
error
Register a callback for errors reported by promise operations.
public function error(callable $onError): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$onError | callable | Callback that receives a promise operation error. |
Return:
self - The current promise.
resolve
Fulfill a pending promise. A second settlement reports a promise operation error.
public function resolve(mixed $value): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$value | mixed | Fulfillment value. |
reject
Reject a pending promise. A second settlement reports a promise operation error.
public function reject(mixed $reason): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$reason | mixed | Reason for the rejection. |
cancel
Cancel a pending promise and set its state to rejected. The cancellation handler, if registered, receives the reason and state.
public function cancel(mixed $reason = null): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$reason | mixed | Cancellation reason. Defaults to null, which supplies a runtime exception. |
wait
Read the settlement value or reason. The method processes queued handlers while the promise is pending. A pending promise with no handlers can return immediately.
public function wait(int $timeout = 1000): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$timeout | int | Timeout in milliseconds. Defaults to 1000. |
Return:
mixed - The stored value or rejection reason, or null if still pending without a value.
is
Check the current state.
public function is(string $state = self::FULFILLED): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$state | string | State to check. Defaults to Promise::FULFILLED. |
Return:
bool - Whether the state matches.
state
Read the current state.
public function state(): stringReturn:
string - One of pending, fulfilled, or rejected.
getState
Read the same state as state().
public function getState(): stringReturn:
string - The current state.
value
Read the promise’s currently stored value.
public function value(): mixedReturn:
mixed - The stored value or rejection reason.
Static Utility Methods
from
Create a promise using the same executor or fulfillment-handler rules as the constructor.
public static function from(?callable $onResolved = null): PromiseInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$onResolved | ?callable | Executor or fulfillment callback. Defaults to null. |
Return:
PromiseInterface - The new promise.
Example:
use Luminova\Promise\Promise;
$promise = Promise::from();
$promise->resolve('Settings loaded');
echo $promise->wait();
// Settings loadeddeferred
Create an object that controls a pending promise.
public static function deferred(): DeferredReturn:
Deferred - A new Deferred.
Example:
use Luminova\Promise\Promise;
$deferred = Promise::deferred();
$deferred->promise()->catch(static function (Throwable $failure): void {
echo $failure->getMessage();
});
$deferred->reject(new RuntimeException('Upload failed'));
// Upload faileddelay
Create a promise configured with a delay in milliseconds. For sequential steps, return the next value from each handler as shown in Create and Chain a Promise.
public static function delay(int $ms, mixed $value = null): PromiseInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$ms | int | Delay in milliseconds. |
$value | mixed | Value configured for fulfillment. Defaults to null. |
Return:
PromiseInterface - The promise created for the delayed operation.
await
Execute a callable in a Fiber. If the task completes on its initial run, the promise fulfills with its return value.
public static function await(callable $task, int $timeout = 0, float $delay = 0.1): PromiseInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$task | callable | Task that supplies the fulfillment value. |
$timeout | int | Timeout in seconds. Defaults to 0 for no limit. |
$delay | float | Pause in seconds between Fiber iterations. Defaults to 0.1. |
Return:
PromiseInterface - The promise for the task’s outcome.
Example:
use Luminova\Promise\Promise;
$promise = Promise::await(static fn (): int => array_sum([10, 20, 30]));
echo $promise->wait();
// 60try
Run a callable and wrap its return value or exception in a promise.
public static function try(callable $fn): PromiseInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$fn | callable | Callable to execute. |
Return:
PromiseInterface - A promise for the returned value or thrown exception.
Example:
use Luminova\Promise\Promise;
$promise = Promise::try(static fn (): array => json_decode('{"active":true}', true, 512, JSON_THROW_ON_ERROR));
echo $promise->wait()['active'] ? 'Active' : 'Inactive';
// Activerace
Settle with the first result that completes, whether it fulfills or rejects.
public static function race(iterable $promises): PromiseInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$promises | iterable | Promises or values to race. |
Return:
PromiseInterface - The resulting promise.
all
Combine successful results by their input keys. To inspect both successes and failures for a batch, see the allSettled example.
public static function all(iterable $promises): PromiseInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$promises | array<array-key,PromiseInterface>|Countable&Traversable | Promises in a countable iterable. |
Return:
PromiseInterface - A promise that fulfills with an array<array-key,mixed> keyed by the input keys.
any
Fulfill with a successful value, or reject with the last rejection reason if every input fails.
public static function any(iterable $promises): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$promises | array<array-key,PromiseInterface>|Countable&Traversable | Promises in a countable iterable. |
Return:
self - A promise for the first successful value. An empty input produces a rejection.
Example:
use Luminova\Promise\Promise;
$result = Promise::any([
Promise::try(static fn () => throw new RuntimeException('Primary source unavailable')),
Promise::try(static fn (): string => 'Result from backup'),
])->wait();
echo $result;
// Result from backupallSettled
Collect the outcome of each input after all inputs settle.
public static function allSettled(iterable $promises): PromiseInterfaceParameters:
| Parameter | Type | Description |
|---|---|---|
$promises | array<array-key,PromiseInterface>|Countable&Traversable | Promises in a countable iterable. |
Return:
PromiseInterface - A promise that fulfills with outcomes keyed by the input keys. Each outcome is array{status: 'fulfilled', value: mixed} or array{status: 'rejected', reason: mixed}.
Example:
use Luminova\Promise\Promise;
$outcomes = Promise::allSettled([
Promise::try(static fn (): string => 'Saved'),
Promise::try(static fn () => throw new RuntimeException('Write failed')),
])->wait();
echo implode(', ', array_column($outcomes, 'status'));
// fulfilled, rejected