Skip to content

Commit

Permalink
Fix Promise::when invocation order
Browse files Browse the repository at this point in the history
  • Loading branch information
kelunik committed Dec 23, 2016
1 parent bc1ae18 commit 44bc971
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 19 deletions.
39 changes: 20 additions & 19 deletions lib/Internal/Placeholder.php
Expand Up @@ -17,10 +17,10 @@ trait Placeholder {

/** @var mixed */
private $result;

/** @var callable|\Amp\Internal\WhenQueue|null */
private $onResolved;

/**
* @see \Interop\Async\Promise::when()
*/
Expand Down Expand Up @@ -63,27 +63,28 @@ private function resolve($value = null) {
throw new \Error("Promise has already been resolved");
}

$this->resolved = true;
$this->result = $value;

if ($this->onResolved === null) {
return;
}
try {
while ($this->onResolved !== null) {
$onResolved = $this->onResolved;
$this->onResolved = null;

$onResolved = $this->onResolved;
$this->onResolved = null;
if ($this->result instanceof Promise) {
$this->result->when($onResolved);
return;
}

if ($this->result instanceof Promise) {
$this->result->when($onResolved);
return;
}

try {
$onResolved(null, $this->result);
} catch (\Throwable $exception) {
Loop::defer(static function () use ($exception) {
throw $exception;
});
try {
$onResolved(null, $this->result);
} catch (\Throwable $exception) {
Loop::defer(static function () use ($exception) {
throw $exception;
});
}
}
} finally {
$this->resolved = true;
}
}

Expand Down
30 changes: 30 additions & 0 deletions test/WhenOrderTest.php
@@ -0,0 +1,30 @@
<?php declare(strict_types = 1);

namespace Amp\Test;

use Amp\Deferred;

class WhenOrderTest extends \PHPUnit_Framework_TestCase {
public function testWhenOrder() {
$this->expectOutputString("1234");

$deferred = new Deferred;
$promise = $deferred->promise();

$promise->when(function () use ($promise) {
$promise->when(function () {
printf("%d", 3);
});
printf("%d", 1);
});

$promise->when(function () use ($promise) {
$promise->when(function () {
printf("%d", 4);
});
printf("%d", 2);
});

$deferred->resolve();
}
}

0 comments on commit 44bc971

Please sign in to comment.