Skip to content

Commit

Permalink
Use call in LazyPromise and make class final
Browse files Browse the repository at this point in the history
  • Loading branch information
trowski committed Jun 9, 2017
1 parent f83d36d commit 9757b39
Showing 1 changed file with 5 additions and 19 deletions.
24 changes: 5 additions & 19 deletions lib/LazyPromise.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,21 @@

namespace Amp;

use React\Promise\PromiseInterface as ReactPromise;

/**
* Creates a promise that calls $promisor only when the result of the promise is requested (i.e. onResolve() is called
* on the promise). $promisor can return a promise or any value. If $promisor throws an exception, the promise fails
* with that exception.
* with that exception. If $promisor returns a Generator, it will be run as a coroutine.
*/
class LazyPromise implements Promise {
final class LazyPromise implements Promise {
/** @var callable|null */
private $promisor;

/** @var \Amp\Promise|null */
private $promise;

/**
* @param callable $promisor Function which starts an async operation, returning a Promise or any value.
* @param callable $promisor Function which starts an async operation, returning a Promise (or any value).
* Generators will be run as a coroutine.
*/
public function __construct(callable $promisor) {
$this->promisor = $promisor;
Expand All @@ -30,20 +29,7 @@ public function onResolve(callable $onResolved) {
if ($this->promise === null) {
$provider = $this->promisor;
$this->promisor = null;

try {
$this->promise = $provider();

if ($this->promise instanceof \Generator) {
$this->promise = new Coroutine($this->promise);
} elseif ($this->promise instanceof ReactPromise) {
$this->promise = Promise\adapt($this->promise);
} elseif (!$this->promise instanceof Promise) {
$this->promise = new Success($this->promise);
}
} catch (\Throwable $exception) {
$this->promise = new Failure($exception);
}
$this->promise = call($provider);
}

$this->promise->onResolve($onResolved);
Expand Down

0 comments on commit 9757b39

Please sign in to comment.