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

49 lines
1.5 KiB
PHP
Raw Normal View History

<?php
2016-08-16 06:46:26 +02:00
2016-05-24 05:48:28 +02:00
namespace Amp;
2016-05-21 16:44:52 +02:00
2016-06-01 19:18:11 +02:00
/**
2016-11-14 20:59:21 +01:00
* Creates a promise from a generator function yielding promises.
2016-08-13 18:37:59 +02:00
*
2016-11-14 20:59:21 +01:00
* When a promise is yielded, execution of the generator is interrupted until the promise is resolved. A success
2016-08-13 18:37:59 +02:00
* value is sent into the generator, while a failure reason is thrown into the generator. Using a coroutine,
* asynchronous code can be written without callbacks and be structured like synchronous code.
*
2020-09-29 21:13:30 +02:00
* @deprecated Use {@see await()} and ext-fiber to await promises.
*
* @template-covariant TReturn
* @template-implements Promise<TReturn>
2016-06-01 19:18:11 +02:00
*/
2018-06-18 20:00:01 +02:00
final class Coroutine implements Promise
{
private Promise $promise;
2016-05-21 16:44:52 +02:00
/**
* @param \Generator $generator
* @psalm-param \Generator<mixed,Promise|ReactPromise|array<array-key,
* Promise|ReactPromise>,mixed,Promise<TReturn>|ReactPromise|TReturn> $generator
2016-05-21 16:44:52 +02:00
*/
2018-06-18 20:00:01 +02:00
public function __construct(\Generator $generator)
{
2020-10-03 05:49:35 +02:00
$this->promise = async(static function () use ($generator): mixed {
$yielded = $generator->current();
while ($generator->valid()) {
2019-05-20 20:29:09 +02:00
try {
2020-09-29 21:13:30 +02:00
$yielded = $generator->send(await($yielded));
2019-05-20 20:29:09 +02:00
} catch (\Throwable $exception) {
$yielded = $generator->throw($exception);
}
}
return $generator->getReturn();
});
}
/** @inheritDoc */
public function onResolve(callable $onResolved): void
{
$this->promise->onResolve($onResolved);
}
2016-06-01 19:06:43 +02:00
}