Skip to content

Commit d182bed

Browse files
committed
Cancellation of input promise is not affected
1 parent f1cfed0 commit d182bed

2 files changed

Lines changed: 47 additions & 0 deletions

File tree

README.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,37 @@ is likely one of your smaller problems.
142142
For more details on the promise cancellation, please refer to the
143143
[Promise documentation](https://github.com/reactphp/promise#cancellablepromiseinterface).
144144

145+
#### Input cancellation
146+
147+
Irrespective of the timout handling, you can also explicitly `cancel()` the
148+
input `$promise` at any time.
149+
This means that the `timeout()` handling does not affect cancellation of the
150+
input `$promise`, as demonstrated in the following example:
151+
152+
```php
153+
$promise = accessSomeRemoteResource();
154+
$timeout = Timer\timeout($promise, 10.0, $loop);
155+
156+
$promise->cancel();
157+
```
158+
159+
The registered [cancellation handler](#cancellation-handler) is responsible for
160+
handling the `cancel()` call:
161+
162+
* A described above, a common use involves resource cleanup and will then *reject*
163+
the `Promise`.
164+
If the input `$promise` is being rejected, then the timeout will be aborted
165+
and the resulting promise will also be rejected.
166+
* If the input `$promise` is still pending, then the timout will continue
167+
running until the timer expires.
168+
The same happens if the input `$promise` does not register a
169+
[cancellation handler](#cancellation-handler).
170+
171+
> Note: If you're stuck on legacy versions (PHP 5.3), then the `cancel()` method
172+
is not available, as the Promise cancellation API is currently only available in
173+
[react/promise v2.1.0](https://github.com/reactphp/promise)
174+
which in turn requires PHP 5.4 or up.
175+
145176
#### Collections
146177

147178
If you want to wait for multiple promises to resolve, you can use the normal promise primitives like this:

tests/FunctionTimeoutTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,4 +74,20 @@ public function testPendingCancellableWillBeCancelledOnTimeout()
7474

7575
$this->loop->run();
7676
}
77+
78+
public function testCancelGivenPromiseWillReject()
79+
{
80+
if (!interface_exists('React\Promise\CancellablePromiseInterface', true)) {
81+
$this->markTestSkipped('Your (outdated?) Promise API does not support cancellable promises');
82+
}
83+
84+
$promise = new \React\Promise\Promise(function () { }, function ($resolve, $reject) { $reject(); });
85+
86+
$timeout = Timer\timeout($promise, 0.01, $this->loop);
87+
88+
$promise->cancel();
89+
90+
$this->expectPromiseRejected($promise);
91+
$this->expectPromiseRejected($timeout);
92+
}
7793
}

0 commit comments

Comments
 (0)