2016-12-29 14:09:49 -06:00
|
|
|
<?php
|
2016-08-15 23:46:26 -05:00
|
|
|
|
2016-05-23 22:48:28 -05:00
|
|
|
namespace Amp;
|
2016-05-21 09:44:52 -05:00
|
|
|
|
2016-06-01 12:18:11 -05:00
|
|
|
/**
|
2016-11-14 13:59:21 -06:00
|
|
|
* Creates a promise from a generator function yielding promises.
|
2016-08-13 18:37:59 +02:00
|
|
|
*
|
2016-11-14 13:59:21 -06: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 12:18:11 -05:00
|
|
|
*/
|
2018-06-18 20:00:01 +02:00
|
|
|
final class Coroutine implements Promise
|
|
|
|
{
|
2020-09-26 23:14:17 -05:00
|
|
|
private Promise $promise;
|
2016-05-21 09:44:52 -05: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 09:44:52 -05:00
|
|
|
*/
|
2018-06-18 20:00:01 +02:00
|
|
|
public function __construct(\Generator $generator)
|
|
|
|
{
|
2020-10-02 22:49:35 -05:00
|
|
|
$this->promise = async(static function () use ($generator): mixed {
|
2019-05-14 21:37:08 +02:00
|
|
|
$yielded = $generator->current();
|
2017-08-04 22:50:19 -05:00
|
|
|
|
2020-09-26 22:22:07 -05: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-26 22:22:07 -05:00
|
|
|
$yielded = $generator->throw($exception);
|
2019-05-14 21:37:08 +02:00
|
|
|
}
|
2020-09-26 22:22:07 -05:00
|
|
|
}
|
2019-05-14 21:37:08 +02:00
|
|
|
|
2020-09-26 22:22:07 -05:00
|
|
|
return $generator->getReturn();
|
2020-09-26 23:14:17 -05:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/** @inheritDoc */
|
|
|
|
public function onResolve(callable $onResolved): void
|
|
|
|
{
|
|
|
|
$this->promise->onResolve($onResolved);
|
2016-06-14 22:35:28 -05:00
|
|
|
}
|
2016-06-01 12:06:43 -05:00
|
|
|
}
|