Skip to content

Commit d460d70

Browse files
committed
Calling cancel() on coroutine should cancel pending promise
1 parent e018573 commit d460d70

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

src/functions.php

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -224,10 +224,16 @@ function coroutine(callable $function, ...$args): PromiseInterface
224224
return resolve($generator);
225225
}
226226

227-
$deferred = new Deferred();
227+
$promise = null;
228+
$deferred = new Deferred(function () use (&$promise) {
229+
if ($promise instanceof CancellablePromiseInterface) {
230+
$promise->cancel();
231+
}
232+
$promise = null;
233+
});
228234

229235
/** @var callable $next */
230-
$next = function () use ($deferred, $generator, &$next) {
236+
$next = function () use ($deferred, $generator, &$next, &$promise) {
231237
try {
232238
if (!$generator->valid()) {
233239
$deferred->resolve($generator->getReturn());

tests/CoroutineTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace React\Tests\Async;
44

5+
use React\Promise\Promise;
56
use function React\Async\coroutine;
67
use function React\Promise\reject;
78
use function React\Promise\resolve;
@@ -104,4 +105,17 @@ public function testCoroutineReturnsRejectedPromiseIfFunctionYieldsInvalidValue(
104105

105106
$promise->then(null, $this->expectCallableOnceWith(new \UnexpectedValueException('Expected coroutine to yield React\Promise\PromiseInterface, but got integer')));
106107
}
108+
109+
public function testCoroutineWillCancelPendingPromiseWhenCallingCancelOnResultingPromise()
110+
{
111+
$promise = coroutine(function () {
112+
yield new Promise(function () { }, function () {
113+
throw new \RuntimeException('Operation cancelled', 42);
114+
});
115+
});
116+
117+
$promise->cancel();
118+
119+
$promise->then(null, $this->expectCallableOnceWith(new \RuntimeException('Operation cancelled', 42)));
120+
}
107121
}

0 commit comments

Comments
 (0)