diff --git a/src/promise/Promise.php b/src/promise/Promise.php index e7188197c..bafec0979 100644 --- a/src/promise/Promise.php +++ b/src/promise/Promise.php @@ -41,8 +41,11 @@ final class Promise{ * @phpstan-param \Closure() : void $onFailure */ public function onCompletion(\Closure $onSuccess, \Closure $onFailure) : void{ - if($this->shared->resolved){ - $this->shared->result === null ? $onFailure() : $onSuccess($this->shared->result); + $state = $this->shared->state; + if($state === true){ + $onSuccess($this->shared->result); + }elseif($state === false){ + $onFailure(); }else{ $this->shared->onSuccess[spl_object_id($onSuccess)] = $onSuccess; $this->shared->onFailure[spl_object_id($onFailure)] = $onFailure; @@ -50,6 +53,8 @@ final class Promise{ } public function isResolved() : bool{ - return $this->shared->resolved; + //TODO: perhaps this should return true when rejected? currently there's no way to tell if a promise was + //rejected or just hasn't been resolved yet + return $this->shared->state === true; } } diff --git a/src/promise/PromiseResolver.php b/src/promise/PromiseResolver.php index 97b181d0b..2019f261d 100644 --- a/src/promise/PromiseResolver.php +++ b/src/promise/PromiseResolver.php @@ -41,10 +41,10 @@ final class PromiseResolver{ * @phpstan-param TValue $value */ public function resolve(mixed $value) : void{ - if($this->shared->resolved){ + if($this->shared->state !== null){ throw new \LogicException("Promise has already been resolved/rejected"); } - $this->shared->resolved = true; + $this->shared->state = true; $this->shared->result = $value; foreach($this->shared->onSuccess as $c){ $c($value); @@ -54,10 +54,10 @@ final class PromiseResolver{ } public function reject() : void{ - if($this->shared->resolved){ + if($this->shared->state !== null){ throw new \LogicException("Promise has already been resolved/rejected"); } - $this->shared->resolved = true; + $this->shared->state = false; foreach($this->shared->onFailure as $c){ $c(); } diff --git a/src/promise/PromiseSharedData.php b/src/promise/PromiseSharedData.php index be667eadb..8bc2691f4 100644 --- a/src/promise/PromiseSharedData.php +++ b/src/promise/PromiseSharedData.php @@ -41,8 +41,8 @@ final class PromiseSharedData{ */ public array $onFailure = []; - public bool $resolved = false; + public ?bool $state = null; - /** @phpstan-var TValue|null */ - public mixed $result = null; + /** @phpstan-var TValue */ + public mixed $result; } diff --git a/tests/phpunit/promise/PromiseTest.php b/tests/phpunit/promise/PromiseTest.php new file mode 100644 index 000000000..7198f4f61 --- /dev/null +++ b/tests/phpunit/promise/PromiseTest.php @@ -0,0 +1,42 @@ +resolve(null); + $resolver->getPromise()->onCompletion( + function(mixed $value) : void{ + self::assertNull($value); + }, + function() : void{ + self::fail("Promise should not be rejected"); + } + ); + } +}