1
0
mirror of https://github.com/danog/amp.git synced 2024-12-03 18:07:57 +01:00
amp/lib/LazyPromise.php

45 lines
1.1 KiB
PHP
Raw Normal View History

<?php
2016-08-16 06:46:26 +02:00
namespace Amp;
2016-05-21 16:44:52 +02:00
2016-06-01 19:18:11 +02: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.
2016-06-01 19:18:11 +02:00
*/
2018-06-18 20:00:01 +02:00
final class LazyPromise implements Promise
{
2016-08-18 05:25:54 +02:00
/** @var callable|null */
private $promisor;
2016-05-21 16:44:52 +02:00
2020-03-28 21:55:44 +01:00
/** @var Promise|null */
private ?Promise $promise;
2016-05-21 16:44:52 +02: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 16:44:52 +02:00
*/
2018-06-18 20:00:01 +02:00
public function __construct(callable $promisor)
{
$this->promisor = $promisor;
2016-05-21 16:44:52 +02:00
}
/**
* @inheritDoc
2016-05-21 16:44:52 +02:00
*/
2020-09-24 18:52:22 +02:00
public function onResolve(callable $onResolved): void
2018-06-18 20:00:01 +02:00
{
if (!isset($this->promise)) {
2020-03-28 21:55:44 +01:00
\assert($this->promisor !== null);
$provider = $this->promisor;
$this->promisor = null;
$this->promise = async($provider);
2016-05-21 16:44:52 +02:00
}
2020-03-28 21:55:44 +01:00
\assert($this->promise !== null);
$this->promise->onResolve($onResolved);
2016-05-21 16:44:52 +02:00
}
}