1
0
mirror of https://github.com/danog/amp.git synced 2025-01-22 05:11:42 +01:00
amp/lib/LazyPromise.php

41 lines
1.1 KiB
PHP
Raw Normal View History

<?php
2016-08-15 23:46:26 -05:00
namespace Amp;
2016-05-21 09:44:52 -05:00
2016-06-01 12:18:11 -05:00
/**
* 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. If $promisor returns a Generator, it will be run as a coroutine.
2016-06-01 12:18:11 -05:00
*/
2018-06-18 20:00:01 +02:00
final class LazyPromise implements Promise
{
2016-08-17 22:25:54 -05:00
/** @var callable|null */
private $promisor;
2016-05-21 09:44:52 -05:00
/** @var \Amp\Promise|null */
2016-11-14 13:59:21 -06:00
private $promise;
2016-05-21 09:44:52 -05:00
/**
* @param callable $promisor Function which starts an async operation, returning a Promise (or any value).
* Generators will be run as a coroutine.
2016-05-21 09:44:52 -05:00
*/
2018-06-18 20:00:01 +02:00
public function __construct(callable $promisor)
{
$this->promisor = $promisor;
2016-05-21 09:44:52 -05:00
}
/**
2016-06-01 12:10:46 -05:00
* {@inheritdoc}
2016-05-21 09:44:52 -05:00
*/
2018-06-18 20:00:01 +02:00
public function onResolve(callable $onResolved)
{
if ($this->promise === null) {
$provider = $this->promisor;
$this->promisor = null;
$this->promise = call($provider);
2016-05-21 09:44:52 -05:00
}
$this->promise->onResolve($onResolved);
2016-05-21 09:44:52 -05:00
}
}