2016-12-29 21:09:49 +01:00
|
|
|
<?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-03-28 12:23:46 +01:00
|
|
|
*
|
2020-09-29 21:13:30 +02:00
|
|
|
* @deprecated Use {@see await()} and ext-fiber to await promises.
|
|
|
|
*
|
2020-03-28 12:23:46 +01:00
|
|
|
* @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
|
|
|
|
{
|
2020-09-27 06:14:17 +02:00
|
|
|
private Promise $promise;
|
2016-05-21 16:44:52 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @param \Generator $generator
|
2020-03-28 13:52:48 +01:00
|
|
|
* @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 {
|
2019-05-14 21:37:08 +02:00
|
|
|
$yielded = $generator->current();
|
2017-08-05 05:50:19 +02:00
|
|
|
|
2020-09-27 05:22:07 +02:00
|
|
|
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) {
|
2020-09-27 05:22:07 +02:00
|
|
|
$yielded = $generator->throw($exception);
|
2019-05-14 21:37:08 +02:00
|
|
|
}
|
2020-09-27 05:22:07 +02:00
|
|
|
}
|
2019-05-14 21:37:08 +02:00
|
|
|
|
2020-09-27 05:22:07 +02:00
|
|
|
return $generator->getReturn();
|
2020-09-27 06:14:17 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/** @inheritDoc */
|
|
|
|
public function onResolve(callable $onResolved): void
|
|
|
|
{
|
|
|
|
$this->promise->onResolve($onResolved);
|
2016-06-15 05:35:28 +02:00
|
|
|
}
|
2016-06-01 19:06:43 +02:00
|
|
|
}
|