Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 107 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add a very simple example how we can consume an AsyncInteropPromise? Such as passing this through the resolve() function etc.?


```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
Expand Down Expand Up @@ -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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: "The AsyncInterop\Promise interface allows interoperability with other promise implementations and their combinator and coroutine implementations."

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kelunik While I understand your point, I actually prefer the current version (which is slightly more conservative and less enthusiastic). After all, while we all aim for this, "allows interoperability" has yet to be proven :-)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jsor Can we add a very simple example to show how this interoperability may look like from a consumer perspective? Such as a dummy combinator function with the proper typehint etc.?

See also above for the documentation and/or example on how we can consume an AsyncInteropPromise.


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
--------

Expand Down
4 changes: 3 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
15 changes: 14 additions & 1 deletion src/FulfilledPromise.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.');
}

Expand Down Expand Up @@ -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);
}
}
}
5 changes: 5 additions & 0 deletions src/LazyPromise.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
11 changes: 11 additions & 0 deletions src/Promise.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
4 changes: 3 additions & 1 deletion src/PromiseInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

namespace React\Promise;

interface PromiseInterface
use AsyncInterop\Promise as AsyncInteropPromise;

interface PromiseInterface extends AsyncInteropPromise
{
/**
* @return PromiseInterface
Expand Down
18 changes: 17 additions & 1 deletion src/RejectedPromise.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.');
}

Expand Down Expand Up @@ -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);
}
}
}
23 changes: 23 additions & 0 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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);
}

Expand Down
20 changes: 20 additions & 0 deletions tests/AsyncInterop/DeferredTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace React\Promise\AsyncInterop;

use AsyncInterop\Promise\Test;
use React\Promise\Deferred;

class DeferredTest extends Test
{
public function promise(callable $canceller = null)
{
$d = new Deferred($canceller);

return [
$d->promise(),
[$d, 'resolve'],
[$d, 'reject']
];
}
}
25 changes: 25 additions & 0 deletions tests/AsyncInterop/LazyPromiseTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace React\Promise\AsyncInterop;

use AsyncInterop\Promise\Test;
use React\Promise\Deferred;
use React\Promise\LazyPromise;

class LazyPromiseTest extends Test
{
public function promise(callable $canceller = null)
{
$d = new Deferred($canceller);

$factory = function () use ($d) {
return $d->promise();
};

return [
new LazyPromise($factory),
[$d, 'resolve'],
[$d, 'reject']
];
}
}
25 changes: 25 additions & 0 deletions tests/AsyncInterop/PromiseTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace React\Promise\AsyncInterop;

use AsyncInterop\Promise\Test;
use React\Promise\Promise;

class PromiseTest extends Test
{
public function promise(callable $canceller = null)
{
$resolveCallback = $rejectCallback = null;

$promise = new Promise(function ($resolve, $reject) use (&$resolveCallback, &$rejectCallback) {
$resolveCallback = $resolve;
$rejectCallback = $reject;
}, $canceller);

return [
$promise,
$resolveCallback,
$rejectCallback
];
}
}
8 changes: 8 additions & 0 deletions tests/FulfilledPromiseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,12 @@ public function shouldThrowExceptionIfConstructedWithAPromise()

return new FulfilledPromise(new FulfilledPromise());
}

/** @test */
public function shouldThrowExceptionIfConstructedWithAAsyncInteropPromise()
{
$this->setExpectedException('\InvalidArgumentException');

return new FulfilledPromise(new SimpleFulfilledAsyncInteropTestPromise());
}
}
Loading