Promise
Promises/A implementation for PHP.
Install / Use
/learn @reactphp/PromiseREADME
Promise
A lightweight implementation of CommonJS Promises/A for PHP.
Table of Contents
- Introduction
- Concepts
- API
- Examples
- Install
- Tests
- Credits
- License
Introduction
Promise is a library implementing CommonJS Promises/A for PHP.
It also provides several other useful promise-related concepts, such as joining multiple promises and mapping and reducing collections of promises.
If you've never heard about promises before, read this first.
Concepts
Deferred
A Deferred represents a computation or unit of work that may not have completed yet. Typically (but not always), that computation will be something that executes asynchronously and completes at some point in the future.
Promise
While a deferred represents the computation itself, a Promise represents the result of that computation. Thus, each deferred has a promise that acts as a placeholder for its actual result.
API
Deferred
A deferred represents an operation whose resolution is pending. It has separate promise and resolver parts.
$deferred = new React\Promise\Deferred();
$promise = $deferred->promise();
$deferred->resolve(mixed $value);
$deferred->reject(\Throwable $reason);
The promise method returns the promise of the deferred.
The resolve and reject methods control the state of the deferred.
The constructor of the Deferred accepts an optional $canceller argument.
See Promise for more information.
Deferred::promise()
$promise = $deferred->promise();
Returns the promise of the deferred, which you can hand out to others while keeping the authority to modify its state to yourself.
Deferred::resolve()
$deferred->resolve(mixed $value);
Resolves the promise returned by promise(). All consumers are notified by
having $onFulfilled (which they registered via $promise->then()) called with
$value.
If $value itself is a promise, the promise will transition to the state of
this promise once it is resolved.
See also the resolve() function.
Deferred::reject()
$deferred->reject(\Throwable $reason);
Rejects the promise returned by promise(), signalling that the deferred's
computation failed.
All consumers are notified by having $onRejected (which they registered via
$promise->then()) called with $reason.
See also the reject() function.
PromiseInterface
The promise interface provides the common interface for all promise implementations. See Promise for the only public implementation exposed by this package.
A promise represents an eventual outcome, which is either fulfillment (success) and an associated value, or rejection (failure) and an associated reason.
Once in the fulfilled or rejected state, a promise becomes immutable. Neither its state nor its result (or error) can be modified.
PromiseInterface::then()
$transformedPromise = $promise->then(callable $onFulfilled = null, callable $onRejected = null);
Transforms a promise's value by applying a function to the promise's fulfillment or rejection value. Returns a new promise for the transformed result.
The then() method registers new fulfilled and rejection handlers with a promise
(all parameters are optional):
$onFulfilledwill be invoked once the promise is fulfilled and passed the result as the first argument.$onRejectedwill be invoked once the promise is rejected and passed the reason as the first argument.
It returns a new promise that will fulfill with the return value of either
$onFulfilled or $onRejected, whichever is called, or will reject with
the thrown exception if either throws.
A promise makes the following guarantees about handlers registered in
the same call to then():
- Only one of
$onFulfilledor$onRejectedwill be called, never both. $onFulfilledand$onRejectedwill never be called more than once.
See also
PromiseInterface::catch()
$promise->catch(callable $onRejected);
Registers a rejection handler for promise. It is a shortcut for:
$promise->then(null, $onRejected);
Additionally, you can type hint the $reason argument of $onRejected to catch
only specific errors.
$promise
->catch(function (\RuntimeException $reason) {
// Only catch \RuntimeException instances
// All other types of errors will propagate automatically
})
->catch(function (\Throwable $reason) {
// Catch other errors
});
PromiseInterface::finally()
$newPromise = $promise->finally(callable $onFulfilledOrRejected);
Allows you to execute "cleanup" type tasks in a promise chain.
It arranges for $onFulfilledOrRejected to be called, with no arguments,
when the promise is either fulfilled or rejected.
- If
$promisefulfills, and$onFulfilledOrRejectedreturns successfully,$newPromisewill fulfill with the same value as$promise. - If
$promisefulfills, and$onFulfilledOrRejectedthrows or returns a rejected promise,$newPromisewill reject with the thrown exception or rejected promise's reason. - If
$promiserejects, and$onFulfilledOrRejectedreturns successfully,$newPromisewill reject with the same reason as$promise. - If
$promiserejects, and$onFulfilledOrRejectedthrows or returns a rejected promise,$newPromisewill reject with the thrown exception or rejected promise's reason.
finally() behaves similarly to the synchronous finally statement. When combined
with catch(), finally() allows you to write code that is similar to the familiar
synchronous catch/finally pair.
Consider the following synchronous code:
try {
return doSomething();
} catch (\Throwable $e) {
return handleError($e);
} finally {
cleanup();
}
Similar asynchronous code (with doSomething() that returns a promise) can be
written:
return doSomething()
->catch('handleError')
->finally('cleanup');
PromiseInterface::cancel()
$promise->cancel();
The cancel() method notifies the creator of the promise that there is no
further interest in the results of the operation.
Once a promise is settled (either fulfilled or rejected), calling cancel() on
a promise has no effect.
~~PromiseInterface::otherwise()~~
Deprecated since v3.0.0, see
catch()instead.
The otherwise() method registers a rejection handler for a promise.
This method continues to exist only for BC reasons and to ease upgrading between versions. It is an alias for:
$promise->catch($onRejected);
~~PromiseInterface::always()~~
Deprecated since v3.0.0, see
finally()instead.
The always() method allows you to execute "cleanup" type tasks in a promise chain.
This method continues to exist only for BC reasons and to ease upgrading between versions. It is an alias for:
$promise->finally($onFulfilledOrRejected);
Promise
Creates a promise whose state is controlled by the functions passed to
$resolver.
$resolver = function (callable $resolve, callable $reject) {
// Do some work, possibly asynchronously, and then
// resolve or reject.
$resolve($awesomeResult);
// or throw new Exception('Promise rejected');
// or $resolve($anotherPromise);
// or $reject($nastyError);
};
$canceller = function () {
// Cancel/abort any running operations like network connections, streams etc.
// Reject promise by throwing an exception
throw new Exception('Promise cancelled');
};
$promise = new React\Promise\Promise($resolver, $canceller);
The promise constructor receives a resolver function and an optional canceller function which both will be called with two arguments:
$resolve($value)- Primary function that seals the fate of the returned promise. Accepts either a non-promise value, or another promise. When called with a non-promise value, fulfills promise with that value. When called with another pro
Related Skills
node-connect
338.7kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
83.6kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
338.7kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
commit-push-pr
83.6kCommit, push, and open a PR
