PHP Luminova: Resolve or Reject a Deferred Promise
Create a pending promise, give it to the code waiting for a result, and settle it when a callback provides a value or reports a failure.
Use Deferred when one part of your application needs a promise before another part knows the outcome. Return promise() to the caller and retain the deferred object in the code that calls resolve() or reject(). For example, a wrapper around a callback-based API can resolve the promise from its success callback and reject it from its failure callback.
Usage
Attach handlers to the promise, then settle it when the result is available. This example resolves it directly so you can see when the success handler runs.
use Luminova\Promise\Deferred;
$deferred = new Deferred();
$deferred->promise()
->then(static function (string $message): void {
echo $message;
})
->catch(static function (Throwable $error): void {
echo $error->getMessage();
});
$deferred->resolve('Operation complete');
// Operation completeOn failure, call $deferred->reject(new RuntimeException('Operation failed')) instead of resolving it. Settle each deferred promise once.
Class Definition
- Full namespace:
Luminova\Promise\Deferred - This class is final.
Methods
__construct
Create a deferred object with a pending promise. You can also create one with Promise::deferred().
public function __construct()promise
Retrieve the same underlying promise for the caller to observe. Attach handlers such as then(), catch(), or finally() to this promise.
public function promise(): PromiseInterfaceReturn:
PromiseInterface - The promise associated with this deferred object.
resolve
Fulfill the pending promise with a result.
public function resolve(mixed $value): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$value | mixed | Result passed to the promise’s fulfillment handler. |
reject
Reject the pending promise with a failure reason.
public function reject(mixed $reason): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$reason | mixed | Failure reason. Pass an exception to preserve its error details. |