diff --git a/README.md b/README.md index 2490c83b..d0ba6b85 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ Table of Contents * [map()](#map) * [reduce()](#reduce) * [PromisorInterface](#promisorinterface) + * [AsyncInterop\Promise compatibility](#asyncinteroppromise-compatibility) 4. [Examples](#examples) * [How to use Deferred](#how-to-use-deferred) * [How promise forwarding works](#how-promise-forwarding-works) @@ -151,6 +152,11 @@ 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. +This interface extends the +[`AsyncInterop\Promise`](https://github.com/async-interop/promise) interface. +See [`AsyncInterop\Promise` compatibility](#asyncinteroppromise-compatibility), +for further information. + #### Implementations * [Promise](#promise-1) @@ -402,11 +408,48 @@ Creates a promise for the supplied `$promiseOrValue`. If `$promiseOrValue` is a value, it will be the resolution value of the returned promise. +```php +React\Promise\resolve(1)->then(function ($value) { + assert(1 === $value); +}); +``` + +If `$promiseOrValue` is a +[`AsyncInterop\Promise`](https://github.com/async-interop/promise), a trusted +promise that follows the state of the `AsyncInterop\Promise` is returned. + +```php +$asyncInteropPromise = getAsyncInteropPromiseWhichResolvesTo1(); + +assert($asyncInteropPromise instanceof AsyncInterop\Promise); + +React\Promise\resolve($asyncInteropPromise)->then(function ($value) { + assert(1 === $value); +}); +``` + If `$promiseOrValue` is a thenable (any object that provides a `then()` method), a trusted promise that follows the state of the thenable is returned. +```php +$thenable = getThenableWhichResolvesTo1(); + +assert(method_exists($thenable, 'then')); + +React\Promise\resolve($asyncInteropPromise)->then(function ($value) { + assert(1 === $value); +}); +``` + If `$promiseOrValue` is a promise, it will be returned as is. +```php +$promise1 = React\Promise\resolve(1); +$promise2 = React\Promise\resolve($promise1); + +assert($promise1 === $promise2); +``` + #### reject() ```php @@ -512,6 +555,70 @@ The `React\Promise\PromisorInterface` provides a common interface for objects that provide a promise. `React\Promise\Deferred` implements it, but since it is part of the public API anyone can implement it. +### AsyncInterop\Promise compatibility + +The [`PromiseInterface`](#promiseinterface) extends the +[`AsyncInterop\Promise`](https://github.com/async-interop/promise) interface and +thereby all promise implementations from React/Promise implement its `when()` +method. + +The `AsyncInterop\Promise` interface is intended for interoperability with other +libraries and their combinator and conversion functions. + +Note, that although the `AsyncInterop\Promise` interface is named *Promise*, +it's API is different from promises commonly known from the +[CommonJS Promises/A](http://wiki.commonjs.org/wiki/Promises/A), +[Promises/A+](https://promisesaplus.com) or +[ECMAScript 2015 (ES6)](http://www.ecma-international.org/ecma-262/6.0/#sec-promise-constructor) +specifications. + +If you're using React/Promise as your primary value placeholder implementation, +it is recommended to **not** use the `when()` method directly but the high level +consumption methods `then()`, `done()`, `otherwise()` and `always()` to consume +a promise's value or reason. + +#### Examples + +You can cast every foreign promise implementing `AsyncInterop\Promise` to a +trusted promise by passing it through [`resolve()`](#resolve). + +It is also possible to return an `AsyncInterop\Promise` instance inside promise +chains. + +```php +$asyncInteropPromise = OtherLib\doAsyncTaskAndReturnAsyncInteropPromise(); + +$reactPromise = React\Promise\resolve($asyncInteropPromise) + ->then(function ($value) { + // You can also return `AsyncInterop\Promise` instances + // from promise handlers + return NextLib\transformValueAndReturnAsyncInteropPromise($value); + }) + ->then(function ($transformedValue) { + + }) +; +``` + +Since promises from React/Promise also implement the `AsyncInterop\Promise` +interface, you can use these promises with combinator, conversion and coroutine +implementations of other libraries which support `AsyncInterop\Promise`. + +```php +$observable = Observable::fromPromise( + $reactSocketClient->connect('google.com:443') +); + +coroutine(function() { + $promiseArray = [ + $reactSocketClient->connect('google.com:443'), + $reactSocketClient->connect('google.de:443') + ]; + + $stream = (yield first($promiseArray)); +}); +``` + Examples -------- diff --git a/composer.json b/composer.json index cec5bf92..f3d67103 100644 --- a/composer.json +++ b/composer.json @@ -6,9 +6,11 @@ {"name": "Jan Sorgalla", "email": "jsorgalla@gmail.com"} ], "require": { - "php": ">=5.4.0" + "php": ">=5.4.0", + "async-interop/promise": "^0.4.0" }, "require-dev": { + "async-interop/promise-test": "^0.4.1", "phpunit/phpunit": "~4.8" }, "autoload": { diff --git a/src/FulfilledPromise.php b/src/FulfilledPromise.php index b28afd82..8108b252 100644 --- a/src/FulfilledPromise.php +++ b/src/FulfilledPromise.php @@ -2,13 +2,15 @@ namespace React\Promise; +use AsyncInterop\Promise as AsyncInteropPromise; + final class FulfilledPromise implements PromiseInterface { private $value; public function __construct($value = null) { - if ($value instanceof PromiseInterface) { + if ($value instanceof AsyncInteropPromise) { throw new \InvalidArgumentException('You cannot create React\Promise\FulfilledPromise with a promise. Use React\Promise\resolve($promiseOrValue) instead.'); } @@ -66,4 +68,15 @@ public function always(callable $onFulfilledOrRejected) public function cancel() { } + + public function when(callable $onResolved) + { + try { + $onResolved(null, $this->value); + } catch (\Throwable $exception) { + AsyncInteropPromise\ErrorHandler::notify($exception); + } catch (\Exception $exception) { + AsyncInteropPromise\ErrorHandler::notify($exception); + } + } } diff --git a/src/LazyPromise.php b/src/LazyPromise.php index 95573406..f735b121 100644 --- a/src/LazyPromise.php +++ b/src/LazyPromise.php @@ -37,6 +37,11 @@ public function cancel() return $this->promise()->cancel(); } + public function when(callable $onResolved) + { + return $this->promise()->when($onResolved); + } + /** * @internal * @see Promise::settle() diff --git a/src/Promise.php b/src/Promise.php index 859606a9..da622f30 100644 --- a/src/Promise.php +++ b/src/Promise.php @@ -86,6 +86,17 @@ public function cancel() $this->call($canceller); } + public function when(callable $onResolved) + { + if (null !== $this->result) { + return $this->result()->when($onResolved); + } + + $this->handlers[] = function (PromiseInterface $promise) use ($onResolved) { + $promise->when($onResolved); + }; + } + private function resolver(callable $onFulfilled = null, callable $onRejected = null) { return function ($resolve, $reject) use ($onFulfilled, $onRejected) { diff --git a/src/PromiseInterface.php b/src/PromiseInterface.php index f926cda5..137a9175 100644 --- a/src/PromiseInterface.php +++ b/src/PromiseInterface.php @@ -2,7 +2,9 @@ namespace React\Promise; -interface PromiseInterface +use AsyncInterop\Promise as AsyncInteropPromise; + +interface PromiseInterface extends AsyncInteropPromise { /** * @return PromiseInterface diff --git a/src/RejectedPromise.php b/src/RejectedPromise.php index 848ac335..5da45088 100644 --- a/src/RejectedPromise.php +++ b/src/RejectedPromise.php @@ -2,13 +2,15 @@ namespace React\Promise; +use AsyncInterop\Promise as AsyncInteropPromise; + final class RejectedPromise implements PromiseInterface { private $reason; public function __construct($reason = null) { - if ($reason instanceof PromiseInterface) { + if ($reason instanceof AsyncInteropPromise) { throw new \InvalidArgumentException('You cannot create React\Promise\RejectedPromise with a promise. Use React\Promise\reject($promiseOrValue) instead.'); } @@ -74,4 +76,18 @@ public function always(callable $onFulfilledOrRejected) public function cancel() { } + + public function when(callable $onResolved) + { + try { + $onResolved( + UnhandledRejectionException::resolve($this->reason), + null + ); + } catch (\Throwable $exception) { + AsyncInteropPromise\ErrorHandler::notify($exception); + } catch (\Exception $exception) { + AsyncInteropPromise\ErrorHandler::notify($exception); + } + } } diff --git a/src/functions.php b/src/functions.php index 40f6639c..fbd84c7e 100644 --- a/src/functions.php +++ b/src/functions.php @@ -2,12 +2,27 @@ namespace React\Promise; +use AsyncInterop\Promise as AsyncInteropPromise; + function resolve($promiseOrValue = null) { if ($promiseOrValue instanceof PromiseInterface) { return $promiseOrValue; } + if ($promiseOrValue instanceof AsyncInteropPromise) { + return new Promise(function ($resolve, $reject) use ($promiseOrValue) { + $promiseOrValue->when(function ($reason = null, $value = null) use ($resolve, $reject) { + if ($reason) { + $reject($reason); + return; + } + + $resolve($value); + }); + }); + } + if (method_exists($promiseOrValue, 'then')) { $canceller = null; @@ -31,6 +46,14 @@ function reject($promiseOrValue = null) }); } + if ($promiseOrValue instanceof AsyncInteropPromise) { + return new Promise(function ($resolve, $reject) use ($promiseOrValue) { + $promiseOrValue->when(function ($reason = null, $value = null) use ($resolve, $reject) { + $reject($reason ? $reason : $value); + }); + }); + } + return new RejectedPromise($promiseOrValue); } diff --git a/tests/AsyncInterop/DeferredTest.php b/tests/AsyncInterop/DeferredTest.php new file mode 100644 index 00000000..4d5e19d1 --- /dev/null +++ b/tests/AsyncInterop/DeferredTest.php @@ -0,0 +1,20 @@ +promise(), + [$d, 'resolve'], + [$d, 'reject'] + ]; + } +} diff --git a/tests/AsyncInterop/LazyPromiseTest.php b/tests/AsyncInterop/LazyPromiseTest.php new file mode 100644 index 00000000..c84ca694 --- /dev/null +++ b/tests/AsyncInterop/LazyPromiseTest.php @@ -0,0 +1,25 @@ +promise(); + }; + + return [ + new LazyPromise($factory), + [$d, 'resolve'], + [$d, 'reject'] + ]; + } +} diff --git a/tests/AsyncInterop/PromiseTest.php b/tests/AsyncInterop/PromiseTest.php new file mode 100644 index 00000000..2df5709d --- /dev/null +++ b/tests/AsyncInterop/PromiseTest.php @@ -0,0 +1,25 @@ +setExpectedException('\InvalidArgumentException'); + + return new FulfilledPromise(new SimpleFulfilledAsyncInteropTestPromise()); + } } diff --git a/tests/FunctionRejectTest.php b/tests/FunctionRejectTest.php index 84b8ec6a..dd4ab7b6 100644 --- a/tests/FunctionRejectTest.php +++ b/tests/FunctionRejectTest.php @@ -42,6 +42,24 @@ public function shouldRejectAFulfilledPromise() ); } + /** @test */ + public function shouldRejectAFulfilledAsyncInteropPromise() + { + $resolved = new SimpleFulfilledAsyncInteropTestPromise(); + + $mock = $this->createCallableMock(); + $mock + ->expects($this->once()) + ->method('__invoke') + ->with($this->identicalTo('foo')); + + reject($resolved) + ->then( + $this->expectCallableNever(), + $mock + ); + } + /** @test */ public function shouldRejectARejectedPromise() { @@ -61,4 +79,23 @@ public function shouldRejectARejectedPromise() $mock ); } + + /** @test */ + public function shouldRejectARejectedAsyncInteropPromise() + { + $exception = new \Exception('foo'); + $resolved = new SimpleRejectedAsyncInteropTestPromise($exception); + + $mock = $this->createCallableMock(); + $mock + ->expects($this->once()) + ->method('__invoke') + ->with($this->identicalTo($exception)); + + reject($resolved) + ->then( + $this->expectCallableNever(), + $mock + ); + } } diff --git a/tests/FunctionResolveTest.php b/tests/FunctionResolveTest.php index 5f1f12e9..afd5087c 100644 --- a/tests/FunctionResolveTest.php +++ b/tests/FunctionResolveTest.php @@ -71,6 +71,24 @@ public function shouldResolveACancellableThenable() $this->assertTrue($thenable->cancelCalled); } + /** @test */ + public function shouldResolveAFulfilledAsyncInteropPromise() + { + $promise = new SimpleFulfilledAsyncInteropTestPromise(); + + $mock = $this->createCallableMock(); + $mock + ->expects($this->once()) + ->method('__invoke') + ->with($this->identicalTo('foo')); + + resolve($promise) + ->then( + $mock, + $this->expectCallableNever() + ); + } + /** @test */ public function shouldRejectARejectedPromise() { @@ -91,6 +109,25 @@ public function shouldRejectARejectedPromise() ); } + /** @test */ + public function shouldRejectARejectedAsyncInteropPromise() + { + $exception = new \Exception('foo'); + $promise = new SimpleRejectedAsyncInteropTestPromise($exception); + + $mock = $this->createCallableMock(); + $mock + ->expects($this->once()) + ->method('__invoke') + ->with($this->identicalTo($exception)); + + resolve($promise) + ->then( + $this->expectCallableNever(), + $mock + ); + } + /** @test */ public function shouldSupportDeepNestingInPromiseChains() { diff --git a/tests/RejectedPromiseTest.php b/tests/RejectedPromiseTest.php index bc2e11bd..e1369116 100644 --- a/tests/RejectedPromiseTest.php +++ b/tests/RejectedPromiseTest.php @@ -44,4 +44,12 @@ public function shouldThrowExceptionIfConstructedWithAPromise() return new RejectedPromise(new RejectedPromise()); } + + /** @test */ + public function shouldThrowExceptionIfConstructedWithAAsyncInteropPromise() + { + $this->setExpectedException('\InvalidArgumentException'); + + return new RejectedPromise(new SimpleFulfilledAsyncInteropTestPromise()); + } } diff --git a/tests/fixtures/SimpleFulfilledAsyncInteropTestPromise.php b/tests/fixtures/SimpleFulfilledAsyncInteropTestPromise.php new file mode 100644 index 00000000..3b43a6ab --- /dev/null +++ b/tests/fixtures/SimpleFulfilledAsyncInteropTestPromise.php @@ -0,0 +1,13 @@ +exception = $exception; + } + + public function when(callable $onResolved) + { + $onResolved($this->exception, null); + } +}