8889841cREADME.md000066600000054521150437342700006043 0ustar00Promise ======= A lightweight implementation of [CommonJS Promises/A](http://wiki.commonjs.org/wiki/Promises/A) for PHP. [![CI status](https://github.com/reactphp/promise/workflows/CI/badge.svg)](https://github.com/reactphp/promise/actions) [![installs on Packagist](https://img.shields.io/packagist/dt/react/promise?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/react/promise) Table of Contents ----------------- 1. [Introduction](#introduction) 2. [Concepts](#concepts) * [Deferred](#deferred) * [Promise](#promise-1) 3. [API](#api) * [Deferred](#deferred-1) * [Deferred::promise()](#deferredpromise) * [Deferred::resolve()](#deferredresolve) * [Deferred::reject()](#deferredreject) * [PromiseInterface](#promiseinterface) * [PromiseInterface::then()](#promiseinterfacethen) * [PromiseInterface::catch()](#promiseinterfacecatch) * [PromiseInterface::finally()](#promiseinterfacefinally) * [PromiseInterface::cancel()](#promiseinterfacecancel) * [~~PromiseInterface::otherwise()~~](#promiseinterfaceotherwise) * [~~PromiseInterface::always()~~](#promiseinterfacealways) * [Promise](#promise-2) * [Functions](#functions) * [resolve()](#resolve) * [reject()](#reject) * [all()](#all) * [race()](#race) * [any()](#any) * [set_rejection_handler()](#set_rejection_handler) 4. [Examples](#examples) * [How to use Deferred](#how-to-use-deferred) * [How promise forwarding works](#how-promise-forwarding-works) * [Resolution forwarding](#resolution-forwarding) * [Rejection forwarding](#rejection-forwarding) * [Mixed resolution and rejection forwarding](#mixed-resolution-and-rejection-forwarding) 5. [Install](#install) 6. [Tests](#tests) 7. [Credits](#credits) 8. [License](#license) Introduction ------------ Promise is a library implementing [CommonJS Promises/A](http://wiki.commonjs.org/wiki/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](https://gist.github.com/domenic/3889970). 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. ```php $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](#promise-2) for more information. #### Deferred::promise() ```php $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() ```php $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](#resolve). #### Deferred::reject() ```php $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](#reject). ### PromiseInterface The promise interface provides the common interface for all promise implementations. See [Promise](#promise-2) 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() ```php $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): * `$onFulfilled` will be invoked once the promise is fulfilled and passed the result as the first argument. * `$onRejected` will 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()`: 1. Only one of `$onFulfilled` or `$onRejected` will be called, never both. 2. `$onFulfilled` and `$onRejected` will never be called more than once. #### See also * [resolve()](#resolve) - Creating a resolved promise * [reject()](#reject) - Creating a rejected promise #### PromiseInterface::catch() ```php $promise->catch(callable $onRejected); ``` Registers a rejection handler for promise. It is a shortcut for: ```php $promise->then(null, $onRejected); ``` Additionally, you can type hint the `$reason` argument of `$onRejected` to catch only specific errors. ```php $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() ```php $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 `$promise` fulfills, and `$onFulfilledOrRejected` returns successfully, `$newPromise` will fulfill with the same value as `$promise`. * If `$promise` fulfills, and `$onFulfilledOrRejected` throws or returns a rejected promise, `$newPromise` will reject with the thrown exception or rejected promise's reason. * If `$promise` rejects, and `$onFulfilledOrRejected` returns successfully, `$newPromise` will reject with the same reason as `$promise`. * If `$promise` rejects, and `$onFulfilledOrRejected` throws or returns a rejected promise, `$newPromise` will 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: ```php try { return doSomething(); } catch (\Throwable $e) { return handleError($e); } finally { cleanup(); } ``` Similar asynchronous code (with `doSomething()` that returns a promise) can be written: ```php return doSomething() ->catch('handleError') ->finally('cleanup'); ``` #### PromiseInterface::cancel() ``` php $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()`](#promiseinterfacecatch) 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: ```php $promise->catch($onRejected); ``` #### ~~PromiseInterface::always()~~ > Deprecated since v3.0.0, see [`finally()`](#promiseinterfacefinally) 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: ```php $promise->finally($onFulfilledOrRejected); ``` ### Promise Creates a promise whose state is controlled by the functions passed to `$resolver`. ```php $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 promise, e.g. `$resolve($otherPromise)`, promise's fate will be equivalent to that of `$otherPromise`. * `$reject($reason)` - Function that rejects the promise. It is recommended to just throw an exception instead of using `$reject()`. If the resolver or canceller throw an exception, the promise will be rejected with that thrown exception as the rejection reason. The resolver function will be called immediately, the canceller function only once all consumers called the `cancel()` method of the promise. ### Functions Useful functions for creating and joining collections of promises. All functions working on promise collections (like `all()`, `race()`, etc.) support cancellation. This means, if you call `cancel()` on the returned promise, all promises in the collection are cancelled. #### resolve() ```php $promise = React\Promise\resolve(mixed $promiseOrValue); ``` Creates a promise for the supplied `$promiseOrValue`. If `$promiseOrValue` is a value, it will be the resolution value of the returned promise. If `$promiseOrValue` is a thenable (any object that provides a `then()` method), a trusted promise that follows the state of the thenable is returned. If `$promiseOrValue` is a promise, it will be returned as is. The resulting `$promise` implements the [`PromiseInterface`](#promiseinterface) and can be consumed like any other promise: ```php $promise = React\Promise\resolve(42); $promise->then(function (int $result): void { var_dump($result); }, function (\Throwable $e): void { echo 'Error: ' . $e->getMessage() . PHP_EOL; }); ``` #### reject() ```php $promise = React\Promise\reject(\Throwable $reason); ``` Creates a rejected promise for the supplied `$reason`. Note that the [`\Throwable`](https://www.php.net/manual/en/class.throwable.php) interface introduced in PHP 7 covers both user land [`\Exception`](https://www.php.net/manual/en/class.exception.php)'s and [`\Error`](https://www.php.net/manual/en/class.error.php) internal PHP errors. By enforcing `\Throwable` as reason to reject a promise, any language error or user land exception can be used to reject a promise. The resulting `$promise` implements the [`PromiseInterface`](#promiseinterface) and can be consumed like any other promise: ```php $promise = React\Promise\reject(new RuntimeException('Request failed')); $promise->then(function (int $result): void { var_dump($result); }, function (\Throwable $e): void { echo 'Error: ' . $e->getMessage() . PHP_EOL; }); ``` Note that rejected promises should always be handled similar to how any exceptions should always be caught in a `try` + `catch` block. If you remove the last reference to a rejected promise that has not been handled, it will report an unhandled promise rejection: ```php function incorrect(): int { $promise = React\Promise\reject(new RuntimeException('Request failed')); // Commented out: No rejection handler registered here. // $promise->then(null, function (\Throwable $e): void { /* ignore */ }); // Returning from a function will remove all local variable references, hence why // this will report an unhandled promise rejection here. return 42; } // Calling this function will log an error message plus its stack trace: // Unhandled promise rejection with RuntimeException: Request failed in example.php:10 incorrect(); ``` A rejected promise will be considered "handled" if you catch the rejection reason with either the [`then()` method](#promiseinterfacethen), the [`catch()` method](#promiseinterfacecatch), or the [`finally()` method](#promiseinterfacefinally). Note that each of these methods return a new promise that may again be rejected if you re-throw an exception. A rejected promise will also be considered "handled" if you abort the operation with the [`cancel()` method](#promiseinterfacecancel) (which in turn would usually reject the promise if it is still pending). See also the [`set_rejection_handler()` function](#set_rejection_handler). #### all() ```php $promise = React\Promise\all(iterable $promisesOrValues); ``` Returns a promise that will resolve only once all the items in `$promisesOrValues` have resolved. The resolution value of the returned promise will be an array containing the resolution values of each of the items in `$promisesOrValues`. #### race() ```php $promise = React\Promise\race(iterable $promisesOrValues); ``` Initiates a competitive race that allows one winner. Returns a promise which is resolved in the same way the first settled promise resolves. The returned promise will become **infinitely pending** if `$promisesOrValues` contains 0 items. #### any() ```php $promise = React\Promise\any(iterable $promisesOrValues); ``` Returns a promise that will resolve when any one of the items in `$promisesOrValues` resolves. The resolution value of the returned promise will be the resolution value of the triggering item. The returned promise will only reject if *all* items in `$promisesOrValues` are rejected. The rejection value will be a `React\Promise\Exception\CompositeException` which holds all rejection reasons. The rejection reasons can be obtained with `CompositeException::getThrowables()`. The returned promise will also reject with a `React\Promise\Exception\LengthException` if `$promisesOrValues` contains 0 items. #### set_rejection_handler() ```php React\Promise\set_rejection_handler(?callable $callback): ?callable; ``` Sets the global rejection handler for unhandled promise rejections. Note that rejected promises should always be handled similar to how any exceptions should always be caught in a `try` + `catch` block. If you remove the last reference to a rejected promise that has not been handled, it will report an unhandled promise rejection. See also the [`reject()` function](#reject) for more details. The `?callable $callback` argument MUST be a valid callback function that accepts a single `Throwable` argument or a `null` value to restore the default promise rejection handler. The return value of the callback function will be ignored and has no effect, so you SHOULD return a `void` value. The callback function MUST NOT throw or the program will be terminated with a fatal error. The function returns the previous rejection handler or `null` if using the default promise rejection handler. The default promise rejection handler will log an error message plus its stack trace: ```php // Unhandled promise rejection with RuntimeException: Unhandled in example.php:2 React\Promise\reject(new RuntimeException('Unhandled')); ``` The promise rejection handler may be used to use customize the log message or write to custom log targets. As a rule of thumb, this function should only be used as a last resort and promise rejections are best handled with either the [`then()` method](#promiseinterfacethen), the [`catch()` method](#promiseinterfacecatch), or the [`finally()` method](#promiseinterfacefinally). See also the [`reject()` function](#reject) for more details. Examples -------- ### How to use Deferred ```php function getAwesomeResultPromise() { $deferred = new React\Promise\Deferred(); // Execute a Node.js-style function using the callback pattern computeAwesomeResultAsynchronously(function (\Throwable $error, $result) use ($deferred) { if ($error) { $deferred->reject($error); } else { $deferred->resolve($result); } }); // Return the promise return $deferred->promise(); } getAwesomeResultPromise() ->then( function ($value) { // Deferred resolved, do something with $value }, function (\Throwable $reason) { // Deferred rejected, do something with $reason } ); ``` ### How promise forwarding works A few simple examples to show how the mechanics of Promises/A forwarding works. These examples are contrived, of course, and in real usage, promise chains will typically be spread across several function calls, or even several levels of your application architecture. #### Resolution forwarding Resolved promises forward resolution values to the next promise. The first promise, `$deferred->promise()`, will resolve with the value passed to `$deferred->resolve()` below. Each call to `then()` returns a new promise that will resolve with the return value of the previous handler. This creates a promise "pipeline". ```php $deferred = new React\Promise\Deferred(); $deferred->promise() ->then(function ($x) { // $x will be the value passed to $deferred->resolve() below // and returns a *new promise* for $x + 1 return $x + 1; }) ->then(function ($x) { // $x === 2 // This handler receives the return value of the // previous handler. return $x + 1; }) ->then(function ($x) { // $x === 3 // This handler receives the return value of the // previous handler. return $x + 1; }) ->then(function ($x) { // $x === 4 // This handler receives the return value of the // previous handler. echo 'Resolve ' . $x; }); $deferred->resolve(1); // Prints "Resolve 4" ``` #### Rejection forwarding Rejected promises behave similarly, and also work similarly to try/catch: When you catch an exception, you must rethrow for it to propagate. Similarly, when you handle a rejected promise, to propagate the rejection, "rethrow" it by either returning a rejected promise, or actually throwing (since promise translates thrown exceptions into rejections) ```php $deferred = new React\Promise\Deferred(); $deferred->promise() ->then(function ($x) { throw new \Exception($x + 1); }) ->catch(function (\Exception $x) { // Propagate the rejection throw $x; }) ->catch(function (\Exception $x) { // Can also propagate by returning another rejection return React\Promise\reject( new \Exception($x->getMessage() + 1) ); }) ->catch(function ($x) { echo 'Reject ' . $x->getMessage(); // 3 }); $deferred->resolve(1); // Prints "Reject 3" ``` #### Mixed resolution and rejection forwarding Just like try/catch, you can choose to propagate or not. Mixing resolutions and rejections will still forward handler results in a predictable way. ```php $deferred = new React\Promise\Deferred(); $deferred->promise() ->then(function ($x) { return $x + 1; }) ->then(function ($x) { throw new \Exception($x + 1); }) ->catch(function (\Exception $x) { // Handle the rejection, and don't propagate. // This is like catch without a rethrow return $x->getMessage() + 1; }) ->then(function ($x) { echo 'Mixed ' . $x; // 4 }); $deferred->resolve(1); // Prints "Mixed 4" ``` Install ------- The recommended way to install this library is [through Composer](https://getcomposer.org/). [New to Composer?](https://getcomposer.org/doc/00-intro.md) This project follows [SemVer](https://semver.org/). This will install the latest supported version from this branch: ```bash composer require react/promise:^3.1 ``` See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. This project aims to run on any platform and thus does not require any PHP extensions and supports running on PHP 7.1 through current PHP 8+. It's *highly recommended to use the latest supported PHP version* for this project. We're committed to providing long-term support (LTS) options and to provide a smooth upgrade path. If you're using an older PHP version, you may use the [`2.x` branch](https://github.com/reactphp/promise/tree/2.x) (PHP 5.4+) or [`1.x` branch](https://github.com/reactphp/promise/tree/1.x) (PHP 5.3+) which both provide a compatible API but do not take advantage of newer language features. You may target multiple versions at the same time to support a wider range of PHP versions like this: ```bash composer require "react/promise:^3 || ^2 || ^1" ``` ## Tests To run the test suite, you first need to clone this repo and then install all dependencies [through Composer](https://getcomposer.org/): ```bash composer install ``` To run the test suite, go to the project root and run: ```bash vendor/bin/phpunit ``` On top of this, we use PHPStan on max level to ensure type safety across the project: ```bash vendor/bin/phpstan ``` Credits ------- Promise is a port of [when.js](https://github.com/cujojs/when) by [Brian Cavalier](https://github.com/briancavalier). Also, large parts of the documentation have been ported from the when.js [Wiki](https://github.com/cujojs/when/wiki) and the [API docs](https://github.com/cujojs/when/blob/master/docs/api.md). License ------- Released under the [MIT](LICENSE) license. CHANGELOG.md000066600000016371150437342700006376 0ustar00# Changelog ## 3.1.0 (2023-11-16) * Feature: Full PHP 8.3 compatibility. (#255 by @clue) * Feature: Describe all callable arguments with types for `Promise` and `Deferred`. (#253 by @clue) * Update test suite and minor documentation improvements. (#251 by @ondrejmirtes and #250 by @SQKo) ## 3.0.0 (2023-07-11) A major new feature release, see [**release announcement**](https://clue.engineering/2023/announcing-reactphp-promise-v3). * We'd like to emphasize that this component is production ready and battle-tested. We plan to support all long-term support (LTS) releases for at least 24 months, so you have a rock-solid foundation to build on top of. * The v3 release will be the way forward for this package. However, we will still actively support v2 and v1 to provide a smooth upgrade path for those not yet on the latest versions. This update involves some major new features and a minor BC break over the `v2.0.0` release. We've tried hard to avoid BC breaks where possible and minimize impact otherwise. We expect that most consumers of this package will be affected by BC breaks, but updating should take no longer than a few minutes. See below for more details: * BC break: PHP 8.1+ recommended, PHP 7.1+ required. (#138 and #149 by @WyriHaximus) * Feature / BC break: The `PromiseInterface` now includes the functionality of the old ~~`ExtendedPromiseInterface`~~ and ~~`CancellablePromiseInterface`~~. Each promise now always includes the `then()`, `catch()`, `finally()` and `cancel()` methods. The new `catch()` and `finally()` methods replace the deprecated ~~`otherwise()`~~ and ~~`always()`~~ methods which continue to exist for BC reasons. The old ~~`ExtendedPromiseInterface`~~ and ~~`CancellablePromiseInterface`~~ are no longer needed and have been removed as a consequence. (#75 by @jsor and #208 by @clue and @WyriHaximus) ```php // old (multiple interfaces may or may not be implemented) assert($promise instanceof PromiseInterface); assert(method_exists($promise, 'then')); if ($promise instanceof ExtendedPromiseInterface) { assert(method_exists($promise, 'otherwise')); } if ($promise instanceof ExtendedPromiseInterface) { assert(method_exists($promise, 'always')); } if ($promise instanceof CancellablePromiseInterface) { assert(method_exists($promise, 'cancel')); } // new (single PromiseInterface with all methods) assert($promise instanceof PromiseInterface); assert(method_exists($promise, 'then')); assert(method_exists($promise, 'catch')); assert(method_exists($promise, 'finally')); assert(method_exists($promise, 'cancel')); ``` * Feature / BC break: Improve type safety of promises. Require `mixed` fulfillment value argument and `Throwable` (or `Exception`) as rejection reason. Add PHPStan template types to ensure strict types for `resolve(T $value): PromiseInterface` and `reject(Throwable $reason): PromiseInterface`. It is no longer possible to resolve a promise without a value (use `null` instead) or reject a promise without a reason (use `Throwable` instead). (#93, #141 and #142 by @jsor, #138, #149 and #247 by @WyriHaximus and #213 and #246 by @clue) ```php // old (arguments used to be optional) $promise = resolve(); $promise = reject(); // new (already supported before) $promise = resolve(null); $promise = reject(new RuntimeException()); ``` * Feature / BC break: Report all unhandled rejections by default and remove ~~`done()`~~ method. Add new `set_rejection_handler()` function to set the global rejection handler for unhandled promise rejections. (#248, #249 and #224 by @clue) ```php // Unhandled promise rejection with RuntimeException: Unhandled in example.php:2 reject(new RuntimeException('Unhandled')); ``` * BC break: Remove all deprecated APIs and reduce API surface. Remove ~~`some()`~~, ~~`map()`~~, ~~`reduce()`~~ functions, use `any()` and `all()` functions instead. Remove internal ~~`FulfilledPromise`~~ and ~~`RejectedPromise`~~ classes, use `resolve()` and `reject()` functions instead. Remove legacy promise progress API (deprecated third argument to `then()` method) and deprecated ~~`LazyPromise`~~ class. (#32 and #98 by @jsor and #164, #219 and #220 by @clue) * BC break: Make all classes final to encourage composition over inheritance. (#80 by @jsor) * Feature / BC break: Require `array` (or `iterable`) type for `all()` + `race()` + `any()` functions and bring in line with ES6 specification. These functions now require a single argument with a variable number of promises or values as input. (#225 by @clue and #35 by @jsor) * Fix / BC break: Fix `race()` to return a forever pending promise when called with an empty `array` (or `iterable`) and bring in line with ES6 specification. (#83 by @jsor and #225 by @clue) * Minor performance improvements by initializing `Deferred` in the constructor and avoiding `call_user_func()` calls. (#151 by @WyriHaximus and #171 by @Kubo2) * Minor documentation improvements. (#110 by @seregazhuk, #132 by @CharlotteDunois, #145 by @danielecr, #178 by @WyriHaximus, #189 by @srdante, #212 by @clue, #214, #239 and #243 by @SimonFrings and #231 by @nhedger) The following changes had to be ported to this release due to our branching strategy, but also appeared in the [`2.x` branch](https://github.com/reactphp/promise/tree/2.x): * Feature: Support union types and address deprecation of `ReflectionType::getClass()` (PHP 8+). (#197 by @cdosoftei and @SimonFrings) * Feature: Support intersection types (PHP 8.1+). (#209 by @bzikarsky) * Feature: Support DNS types (PHP 8.2+). (#236 by @nhedger) * Feature: Port all memory improvements from `2.x` to `3.x`. (#150 by @clue and @WyriHaximus) * Fix: Fix checking whether cancellable promise is an object and avoid possible warning. (#161 by @smscr) * Improve performance by prefixing all global functions calls with \ to skip the look up and resolve process and go straight to the global function. (#134 by @WyriHaximus) * Improve test suite, update PHPUnit and PHP versions and add `.gitattributes` to exclude dev files from exports. (#107 by @carusogabriel, #148 and #234 by @WyriHaximus, #153 by @reedy, #162, #230 and #240 by @clue, #173, #177, #185 and #199 by @SimonFrings, #193 by @woodongwong and #210 by @bzikarsky) The following changes were originally planned for this release but later reverted and are not part of the final release: * Add iterative callback queue handler to avoid recursion (later removed to improve Fiber support). (#28, #82 and #86 by @jsor, #158 by @WyriHaximus and #229 and #238 by @clue) * Trigger an `E_USER_ERROR` instead of throwing an exception from `done()` (later removed entire `done()` method to globally report unhandled rejections). (#97 by @jsor and #224 and #248 by @clue) * Add type declarations for `some()` (later removed entire `some()` function). (#172 by @WyriHaximus and #219 by @clue) ## 2.0.0 (2013-12-10) See [`2.x` CHANGELOG](https://github.com/reactphp/promise/blob/2.x/CHANGELOG.md) for more details. ## 1.0.0 (2012-11-07) See [`1.x` CHANGELOG](https://github.com/reactphp/promise/blob/1.x/CHANGELOG.md) for more details. src/Promise.php000066600000024325150437342700007501 0ustar00 */ final class Promise implements PromiseInterface { /** @var (callable(callable(T):void,callable(\Throwable):void):void)|null */ private $canceller; /** @var ?PromiseInterface */ private $result; /** @var list):void> */ private $handlers = []; /** @var int */ private $requiredCancelRequests = 0; /** @var bool */ private $cancelled = false; /** * @param callable(callable(T):void,callable(\Throwable):void):void $resolver * @param (callable(callable(T):void,callable(\Throwable):void):void)|null $canceller */ public function __construct(callable $resolver, callable $canceller = null) { $this->canceller = $canceller; // Explicitly overwrite arguments with null values before invoking // resolver function. This ensure that these arguments do not show up // in the stack trace in PHP 7+ only. $cb = $resolver; $resolver = $canceller = null; $this->call($cb); } public function then(callable $onFulfilled = null, callable $onRejected = null): PromiseInterface { if (null !== $this->result) { return $this->result->then($onFulfilled, $onRejected); } if (null === $this->canceller) { return new static($this->resolver($onFulfilled, $onRejected)); } // This promise has a canceller, so we create a new child promise which // has a canceller that invokes the parent canceller if all other // followers are also cancelled. We keep a reference to this promise // instance for the static canceller function and clear this to avoid // keeping a cyclic reference between parent and follower. $parent = $this; ++$parent->requiredCancelRequests; return new static( $this->resolver($onFulfilled, $onRejected), static function () use (&$parent): void { assert($parent instanceof self); --$parent->requiredCancelRequests; if ($parent->requiredCancelRequests <= 0) { $parent->cancel(); } $parent = null; } ); } /** * @template TThrowable of \Throwable * @template TRejected * @param callable(TThrowable): (PromiseInterface|TRejected) $onRejected * @return PromiseInterface */ public function catch(callable $onRejected): PromiseInterface { return $this->then(null, static function (\Throwable $reason) use ($onRejected) { if (!_checkTypehint($onRejected, $reason)) { return new RejectedPromise($reason); } /** * @var callable(\Throwable):(PromiseInterface|TRejected) $onRejected */ return $onRejected($reason); }); } public function finally(callable $onFulfilledOrRejected): PromiseInterface { return $this->then(static function ($value) use ($onFulfilledOrRejected): PromiseInterface { return resolve($onFulfilledOrRejected())->then(function () use ($value) { return $value; }); }, static function (\Throwable $reason) use ($onFulfilledOrRejected): PromiseInterface { return resolve($onFulfilledOrRejected())->then(function () use ($reason): RejectedPromise { return new RejectedPromise($reason); }); }); } public function cancel(): void { $this->cancelled = true; $canceller = $this->canceller; $this->canceller = null; $parentCanceller = null; if (null !== $this->result) { // Forward cancellation to rejected promise to avoid reporting unhandled rejection if ($this->result instanceof RejectedPromise) { $this->result->cancel(); } // Go up the promise chain and reach the top most promise which is // itself not following another promise $root = $this->unwrap($this->result); // Return if the root promise is already resolved or a // FulfilledPromise or RejectedPromise if (!$root instanceof self || null !== $root->result) { return; } $root->requiredCancelRequests--; if ($root->requiredCancelRequests <= 0) { $parentCanceller = [$root, 'cancel']; } } if (null !== $canceller) { $this->call($canceller); } // For BC, we call the parent canceller after our own canceller if ($parentCanceller) { $parentCanceller(); } } /** * @deprecated 3.0.0 Use `catch()` instead * @see self::catch() */ public function otherwise(callable $onRejected): PromiseInterface { return $this->catch($onRejected); } /** * @deprecated 3.0.0 Use `finally()` instead * @see self::finally() */ public function always(callable $onFulfilledOrRejected): PromiseInterface { return $this->finally($onFulfilledOrRejected); } private function resolver(callable $onFulfilled = null, callable $onRejected = null): callable { return function (callable $resolve, callable $reject) use ($onFulfilled, $onRejected): void { $this->handlers[] = static function (PromiseInterface $promise) use ($onFulfilled, $onRejected, $resolve, $reject): void { $promise = $promise->then($onFulfilled, $onRejected); if ($promise instanceof self && $promise->result === null) { $promise->handlers[] = static function (PromiseInterface $promise) use ($resolve, $reject): void { $promise->then($resolve, $reject); }; } else { $promise->then($resolve, $reject); } }; }; } private function reject(\Throwable $reason): void { if (null !== $this->result) { return; } $this->settle(reject($reason)); } /** * @param PromiseInterface $result */ private function settle(PromiseInterface $result): void { $result = $this->unwrap($result); if ($result === $this) { $result = new RejectedPromise( new \LogicException('Cannot resolve a promise with itself.') ); } if ($result instanceof self) { $result->requiredCancelRequests++; } else { // Unset canceller only when not following a pending promise $this->canceller = null; } $handlers = $this->handlers; $this->handlers = []; $this->result = $result; foreach ($handlers as $handler) { $handler($result); } // Forward cancellation to rejected promise to avoid reporting unhandled rejection if ($this->cancelled && $result instanceof RejectedPromise) { $result->cancel(); } } /** * @param PromiseInterface $promise * @return PromiseInterface */ private function unwrap(PromiseInterface $promise): PromiseInterface { while ($promise instanceof self && null !== $promise->result) { /** @var PromiseInterface $promise */ $promise = $promise->result; } return $promise; } /** * @param callable(callable(mixed):void,callable(\Throwable):void):void $cb */ private function call(callable $cb): void { // Explicitly overwrite argument with null value. This ensure that this // argument does not show up in the stack trace in PHP 7+ only. $callback = $cb; $cb = null; // Use reflection to inspect number of arguments expected by this callback. // We did some careful benchmarking here: Using reflection to avoid unneeded // function arguments is actually faster than blindly passing them. // Also, this helps avoiding unnecessary function arguments in the call stack // if the callback creates an Exception (creating garbage cycles). if (\is_array($callback)) { $ref = new \ReflectionMethod($callback[0], $callback[1]); } elseif (\is_object($callback) && !$callback instanceof \Closure) { $ref = new \ReflectionMethod($callback, '__invoke'); } else { assert($callback instanceof \Closure || \is_string($callback)); $ref = new \ReflectionFunction($callback); } $args = $ref->getNumberOfParameters(); try { if ($args === 0) { $callback(); } else { // Keep references to this promise instance for the static resolve/reject functions. // By using static callbacks that are not bound to this instance // and passing the target promise instance by reference, we can // still execute its resolving logic and still clear this // reference when settling the promise. This helps avoiding // garbage cycles if any callback creates an Exception. // These assumptions are covered by the test suite, so if you ever feel like // refactoring this, go ahead, any alternative suggestions are welcome! $target =& $this; $callback( static function ($value) use (&$target): void { if ($target !== null) { $target->settle(resolve($value)); $target = null; } }, static function (\Throwable $reason) use (&$target): void { if ($target !== null) { $target->reject($reason); $target = null; } } ); } } catch (\Throwable $e) { $target = null; $this->reject($e); } } } src/Deferred.php000066600000002024150437342700007573 0ustar00 */ private $promise; /** @var callable(T):void */ private $resolveCallback; /** @var callable(\Throwable):void */ private $rejectCallback; /** * @param (callable(callable(T):void,callable(\Throwable):void):void)|null $canceller */ public function __construct(callable $canceller = null) { $this->promise = new Promise(function ($resolve, $reject): void { $this->resolveCallback = $resolve; $this->rejectCallback = $reject; }, $canceller); } /** * @return PromiseInterface */ public function promise(): PromiseInterface { return $this->promise; } /** * @param T $value */ public function resolve($value): void { ($this->resolveCallback)($value); } public function reject(\Throwable $reason): void { ($this->rejectCallback)($reason); } } src/Internal/FulfilledPromise.php000066600000004432150437342700013101 0ustar00 */ final class FulfilledPromise implements PromiseInterface { /** @var T */ private $value; /** * @param T $value * @throws \InvalidArgumentException */ public function __construct($value = null) { if ($value instanceof PromiseInterface) { throw new \InvalidArgumentException('You cannot create React\Promise\FulfilledPromise with a promise. Use React\Promise\resolve($promiseOrValue) instead.'); } $this->value = $value; } /** * @template TFulfilled * @param ?(callable((T is void ? null : T)): (PromiseInterface|TFulfilled)) $onFulfilled * @return PromiseInterface<($onFulfilled is null ? T : TFulfilled)> */ public function then(callable $onFulfilled = null, callable $onRejected = null): PromiseInterface { if (null === $onFulfilled) { return $this; } try { /** * @var PromiseInterface|T $result */ $result = $onFulfilled($this->value); return resolve($result); } catch (\Throwable $exception) { return new RejectedPromise($exception); } } public function catch(callable $onRejected): PromiseInterface { return $this; } public function finally(callable $onFulfilledOrRejected): PromiseInterface { return $this->then(function ($value) use ($onFulfilledOrRejected): PromiseInterface { return resolve($onFulfilledOrRejected())->then(function () use ($value) { return $value; }); }); } public function cancel(): void { } /** * @deprecated 3.0.0 Use `catch()` instead * @see self::catch() */ public function otherwise(callable $onRejected): PromiseInterface { return $this->catch($onRejected); } /** * @deprecated 3.0.0 Use `finally()` instead * @see self::finally() */ public function always(callable $onFulfilledOrRejected): PromiseInterface { return $this->finally($onFulfilledOrRejected); } } src/Internal/CancellationQueue.php000066600000002432150437342700013233 0ustar00started) { return; } $this->started = true; $this->drain(); } /** * @param mixed $cancellable */ public function enqueue($cancellable): void { if (!\is_object($cancellable) || !\method_exists($cancellable, 'then') || !\method_exists($cancellable, 'cancel')) { return; } $length = \array_push($this->queue, $cancellable); if ($this->started && 1 === $length) { $this->drain(); } } private function drain(): void { for ($i = \key($this->queue); isset($this->queue[$i]); $i++) { $cancellable = $this->queue[$i]; assert(\method_exists($cancellable, 'cancel')); $exception = null; try { $cancellable->cancel(); } catch (\Throwable $exception) { } unset($this->queue[$i]); if ($exception) { throw $exception; } } $this->queue = []; } } src/Internal/RejectedPromise.php000066600000007144150437342700012723 0ustar00 */ final class RejectedPromise implements PromiseInterface { /** @var \Throwable */ private $reason; /** @var bool */ private $handled = false; /** * @param \Throwable $reason */ public function __construct(\Throwable $reason) { $this->reason = $reason; } /** @throws void */ public function __destruct() { if ($this->handled) { return; } $handler = set_rejection_handler(null); if ($handler === null) { $message = 'Unhandled promise rejection with ' . \get_class($this->reason) . ': ' . $this->reason->getMessage() . ' in ' . $this->reason->getFile() . ':' . $this->reason->getLine() . PHP_EOL; $message .= 'Stack trace:' . PHP_EOL . $this->reason->getTraceAsString(); \error_log($message); return; } try { $handler($this->reason); } catch (\Throwable $e) { $message = 'Fatal error: Uncaught ' . \get_class($e) . ' from unhandled promise rejection handler: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine() . PHP_EOL; $message .= 'Stack trace:' . PHP_EOL . $e->getTraceAsString(); \error_log($message); exit(255); } } /** * @template TRejected * @param ?callable $onFulfilled * @param ?(callable(\Throwable): (PromiseInterface|TRejected)) $onRejected * @return PromiseInterface<($onRejected is null ? never : TRejected)> */ public function then(callable $onFulfilled = null, callable $onRejected = null): PromiseInterface { if (null === $onRejected) { return $this; } $this->handled = true; try { return resolve($onRejected($this->reason)); } catch (\Throwable $exception) { return new RejectedPromise($exception); } } /** * @template TThrowable of \Throwable * @template TRejected * @param callable(TThrowable): (PromiseInterface|TRejected) $onRejected * @return PromiseInterface */ public function catch(callable $onRejected): PromiseInterface { if (!_checkTypehint($onRejected, $this->reason)) { return $this; } /** * @var callable(\Throwable):(PromiseInterface|TRejected) $onRejected */ return $this->then(null, $onRejected); } public function finally(callable $onFulfilledOrRejected): PromiseInterface { return $this->then(null, function (\Throwable $reason) use ($onFulfilledOrRejected): PromiseInterface { return resolve($onFulfilledOrRejected())->then(function () use ($reason): PromiseInterface { return new RejectedPromise($reason); }); }); } public function cancel(): void { $this->handled = true; } /** * @deprecated 3.0.0 Use `catch()` instead * @see self::catch() */ public function otherwise(callable $onRejected): PromiseInterface { return $this->catch($onRejected); } /** * @deprecated 3.0.0 Use `always()` instead * @see self::always() */ public function always(callable $onFulfilledOrRejected): PromiseInterface { return $this->finally($onFulfilledOrRejected); } } src/functions_include.php000066600000000141150437342700011564 0ustar00|T $promiseOrValue * @return PromiseInterface */ function resolve($promiseOrValue): PromiseInterface { if ($promiseOrValue instanceof PromiseInterface) { return $promiseOrValue; } if (\is_object($promiseOrValue) && \method_exists($promiseOrValue, 'then')) { $canceller = null; if (\method_exists($promiseOrValue, 'cancel')) { $canceller = [$promiseOrValue, 'cancel']; assert(\is_callable($canceller)); } /** @var Promise */ return new Promise(function (callable $resolve, callable $reject) use ($promiseOrValue): void { $promiseOrValue->then($resolve, $reject); }, $canceller); } return new FulfilledPromise($promiseOrValue); } /** * Creates a rejected promise for the supplied `$reason`. * * If `$reason` is a value, it will be the rejection value of the * returned promise. * * If `$reason` is a promise, its completion value will be the rejected * value of the returned promise. * * This can be useful in situations where you need to reject a promise without * throwing an exception. For example, it allows you to propagate a rejection with * the value of another promise. * * @return PromiseInterface */ function reject(\Throwable $reason): PromiseInterface { return new RejectedPromise($reason); } /** * Returns a promise that will resolve only once all the items in * `$promisesOrValues` have resolved. The resolution value of the returned promise * will be an array containing the resolution values of each of the items in * `$promisesOrValues`. * * @template T * @param iterable|T> $promisesOrValues * @return PromiseInterface> */ function all(iterable $promisesOrValues): PromiseInterface { $cancellationQueue = new Internal\CancellationQueue(); /** @var Promise> */ return new Promise(function (callable $resolve, callable $reject) use ($promisesOrValues, $cancellationQueue): void { $toResolve = 0; /** @var bool */ $continue = true; $values = []; foreach ($promisesOrValues as $i => $promiseOrValue) { $cancellationQueue->enqueue($promiseOrValue); $values[$i] = null; ++$toResolve; resolve($promiseOrValue)->then( function ($value) use ($i, &$values, &$toResolve, &$continue, $resolve): void { $values[$i] = $value; if (0 === --$toResolve && !$continue) { $resolve($values); } }, function (\Throwable $reason) use (&$continue, $reject): void { $continue = false; $reject($reason); } ); if (!$continue && !\is_array($promisesOrValues)) { break; } } $continue = false; if ($toResolve === 0) { $resolve($values); } }, $cancellationQueue); } /** * Initiates a competitive race that allows one winner. Returns a promise which is * resolved in the same way the first settled promise resolves. * * The returned promise will become **infinitely pending** if `$promisesOrValues` * contains 0 items. * * @template T * @param iterable|T> $promisesOrValues * @return PromiseInterface */ function race(iterable $promisesOrValues): PromiseInterface { $cancellationQueue = new Internal\CancellationQueue(); /** @var Promise */ return new Promise(function (callable $resolve, callable $reject) use ($promisesOrValues, $cancellationQueue): void { $continue = true; foreach ($promisesOrValues as $promiseOrValue) { $cancellationQueue->enqueue($promiseOrValue); resolve($promiseOrValue)->then($resolve, $reject)->finally(function () use (&$continue): void { $continue = false; }); if (!$continue && !\is_array($promisesOrValues)) { break; } } }, $cancellationQueue); } /** * Returns a promise that will resolve when any one of the items in * `$promisesOrValues` resolves. The resolution value of the returned promise * will be the resolution value of the triggering item. * * The returned promise will only reject if *all* items in `$promisesOrValues` are * rejected. The rejection value will be an array of all rejection reasons. * * The returned promise will also reject with a `React\Promise\Exception\LengthException` * if `$promisesOrValues` contains 0 items. * * @template T * @param iterable|T> $promisesOrValues * @return PromiseInterface */ function any(iterable $promisesOrValues): PromiseInterface { $cancellationQueue = new Internal\CancellationQueue(); /** @var Promise */ return new Promise(function (callable $resolve, callable $reject) use ($promisesOrValues, $cancellationQueue): void { $toReject = 0; $continue = true; $reasons = []; foreach ($promisesOrValues as $i => $promiseOrValue) { $cancellationQueue->enqueue($promiseOrValue); ++$toReject; resolve($promiseOrValue)->then( function ($value) use ($resolve, &$continue): void { $continue = false; $resolve($value); }, function (\Throwable $reason) use ($i, &$reasons, &$toReject, $reject, &$continue): void { $reasons[$i] = $reason; if (0 === --$toReject && !$continue) { $reject(new CompositeException( $reasons, 'All promises rejected.' )); } } ); if (!$continue && !\is_array($promisesOrValues)) { break; } } $continue = false; if ($toReject === 0 && !$reasons) { $reject(new Exception\LengthException( 'Must contain at least 1 item but contains only 0 items.' )); } elseif ($toReject === 0) { $reject(new CompositeException( $reasons, 'All promises rejected.' )); } }, $cancellationQueue); } /** * Sets the global rejection handler for unhandled promise rejections. * * Note that rejected promises should always be handled similar to how any * exceptions should always be caught in a `try` + `catch` block. If you remove * the last reference to a rejected promise that has not been handled, it will * report an unhandled promise rejection. See also the [`reject()` function](#reject) * for more details. * * The `?callable $callback` argument MUST be a valid callback function that * accepts a single `Throwable` argument or a `null` value to restore the * default promise rejection handler. The return value of the callback function * will be ignored and has no effect, so you SHOULD return a `void` value. The * callback function MUST NOT throw or the program will be terminated with a * fatal error. * * The function returns the previous rejection handler or `null` if using the * default promise rejection handler. * * The default promise rejection handler will log an error message plus its * stack trace: * * ```php * // Unhandled promise rejection with RuntimeException: Unhandled in example.php:2 * React\Promise\reject(new RuntimeException('Unhandled')); * ``` * * The promise rejection handler may be used to use customize the log message or * write to custom log targets. As a rule of thumb, this function should only be * used as a last resort and promise rejections are best handled with either the * [`then()` method](#promiseinterfacethen), the * [`catch()` method](#promiseinterfacecatch), or the * [`finally()` method](#promiseinterfacefinally). * See also the [`reject()` function](#reject) for more details. * * @param callable(\Throwable):void|null $callback * @return callable(\Throwable):void|null */ function set_rejection_handler(?callable $callback): ?callable { static $current = null; $previous = $current; $current = $callback; return $previous; } /** * @internal */ function _checkTypehint(callable $callback, \Throwable $reason): bool { if (\is_array($callback)) { $callbackReflection = new \ReflectionMethod($callback[0], $callback[1]); } elseif (\is_object($callback) && !$callback instanceof \Closure) { $callbackReflection = new \ReflectionMethod($callback, '__invoke'); } else { assert($callback instanceof \Closure || \is_string($callback)); $callbackReflection = new \ReflectionFunction($callback); } $parameters = $callbackReflection->getParameters(); if (!isset($parameters[0])) { return true; } $expectedException = $parameters[0]; // Extract the type of the argument and handle different possibilities $type = $expectedException->getType(); $isTypeUnion = true; $types = []; switch (true) { case $type === null: break; case $type instanceof \ReflectionNamedType: $types = [$type]; break; case $type instanceof \ReflectionIntersectionType: $isTypeUnion = false; case $type instanceof \ReflectionUnionType; $types = $type->getTypes(); break; default: throw new \LogicException('Unexpected return value of ReflectionParameter::getType'); } // If there is no type restriction, it matches if (empty($types)) { return true; } foreach ($types as $type) { if ($type instanceof \ReflectionIntersectionType) { foreach ($type->getTypes() as $typeToMatch) { assert($typeToMatch instanceof \ReflectionNamedType); $name = $typeToMatch->getName(); if (!($matches = (!$typeToMatch->isBuiltin() && $reason instanceof $name))) { break; } } assert(isset($matches)); } else { assert($type instanceof \ReflectionNamedType); $name = $type->getName(); $matches = !$type->isBuiltin() && $reason instanceof $name; } // If we look for a single match (union), we can return early on match // If we look for a full match (intersection), we can return early on mismatch if ($matches) { if ($isTypeUnion) { return true; } } else { if (!$isTypeUnion) { return false; } } } // If we look for a single match (union) and did not return early, we matched no type and are false // If we look for a full match (intersection) and did not return early, we matched all types and are true return $isTypeUnion ? false : true; } src/Exception/LengthException.php000066600000000136150437342700013113 0ustar00throwables = $throwables; } /** * @return \Throwable[] */ public function getThrowables(): array { return $this->throwables; } } src/PromiseInterface.php000066600000013131150437342700011313 0ustar00|TFulfilled)) $onFulfilled * @param ?(callable(\Throwable): (PromiseInterface|TRejected)) $onRejected * @return PromiseInterface<($onRejected is null ? ($onFulfilled is null ? T : TFulfilled) : ($onFulfilled is null ? T|TRejected : TFulfilled|TRejected))> */ public function then(?callable $onFulfilled = null, ?callable $onRejected = null): PromiseInterface; /** * Registers a rejection handler for promise. It is a shortcut for: * * ```php * $promise->then(null, $onRejected); * ``` * * Additionally, you can type hint the `$reason` argument of `$onRejected` to catch * only specific errors. * * @template TThrowable of \Throwable * @template TRejected * @param callable(TThrowable): (PromiseInterface|TRejected) $onRejected * @return PromiseInterface */ public function catch(callable $onRejected): PromiseInterface; /** * 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 `$promise` fulfills, and `$onFulfilledOrRejected` returns successfully, * `$newPromise` will fulfill with the same value as `$promise`. * * If `$promise` fulfills, and `$onFulfilledOrRejected` throws or returns a * rejected promise, `$newPromise` will reject with the thrown exception or * rejected promise's reason. * * If `$promise` rejects, and `$onFulfilledOrRejected` returns successfully, * `$newPromise` will reject with the same reason as `$promise`. * * If `$promise` rejects, and `$onFulfilledOrRejected` throws or returns a * rejected promise, `$newPromise` will 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: * * ```php * try { * return doSomething(); * } catch(\Exception $e) { * return handleError($e); * } finally { * cleanup(); * } * ``` * * Similar asynchronous code (with `doSomething()` that returns a promise) can be * written: * * ```php * return doSomething() * ->catch('handleError') * ->finally('cleanup'); * ``` * * @param callable(): (void|PromiseInterface) $onFulfilledOrRejected * @return PromiseInterface */ public function finally(callable $onFulfilledOrRejected): PromiseInterface; /** * 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. * * @return void */ public function cancel(): void; /** * [Deprecated] 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: * * ```php * $promise->catch($onRejected); * ``` * * @template TThrowable of \Throwable * @template TRejected * @param callable(TThrowable): (PromiseInterface|TRejected) $onRejected * @return PromiseInterface * @deprecated 3.0.0 Use catch() instead * @see self::catch() */ public function otherwise(callable $onRejected): PromiseInterface; /** * [Deprecated] 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: * * ```php * $promise->finally($onFulfilledOrRejected); * ``` * * @param callable(): (void|PromiseInterface) $onFulfilledOrRejected * @return PromiseInterface * @deprecated 3.0.0 Use finally() instead * @see self::finally() */ public function always(callable $onFulfilledOrRejected): PromiseInterface; } composer.json000066600000002564150437342700007306 0ustar00{ "name": "react/promise", "description": "A lightweight implementation of CommonJS Promises/A for PHP", "license": "MIT", "authors": [ { "name": "Jan Sorgalla", "homepage": "https://sorgalla.com/", "email": "jsorgalla@gmail.com" }, { "name": "Christian Lück", "homepage": "https://clue.engineering/", "email": "christian@clue.engineering" }, { "name": "Cees-Jan Kiewiet", "homepage": "https://wyrihaximus.net/", "email": "reactphp@ceesjankiewiet.nl" }, { "name": "Chris Boden", "homepage": "https://cboden.dev/", "email": "cboden@gmail.com" } ], "require": { "php": ">=7.1.0" }, "require-dev": { "phpstan/phpstan": "1.10.39 || 1.4.10", "phpunit/phpunit": "^9.6 || ^7.5" }, "autoload": { "psr-4": { "React\\Promise\\": "src/" }, "files": [ "src/functions_include.php" ] }, "autoload-dev": { "psr-4": { "React\\Promise\\": [ "tests/fixtures/", "tests/" ] }, "files": [ "tests/Fiber.php" ] }, "keywords": [ "promise", "promises" ] } LICENSE000066600000002147150437342700005566 0ustar00The MIT License (MIT) Copyright (c) 2012 Jan Sorgalla, Christian Lück, Cees-Jan Kiewiet, Chris Boden Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.