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
|
|
|
/**
|
2020-09-27 05:22:07 +02:00
|
|
|
* @deprecated Use {@see await()} and ext-fiber to await promises.
|
|
|
|
*
|
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
|
|
|
*
|
|
|
|
* @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
|
|
|
|
{
|
2016-05-21 16:44:52 +02:00
|
|
|
use Internal\Placeholder;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @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-09-27 05:22:07 +02:00
|
|
|
$this->resolve(async(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-27 05:22:07 +02:00
|
|
|
$value = 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);
|
|
|
|
continue;
|
2019-05-14 21:37:08 +02:00
|
|
|
}
|
2016-05-21 16:44:52 +02:00
|
|
|
|
2020-09-27 05:22:07 +02:00
|
|
|
$yielded = $generator->send($value);
|
|
|
|
}
|
2019-05-14 21:37:08 +02:00
|
|
|
|
2020-09-27 05:22:07 +02:00
|
|
|
return $generator->getReturn();
|
|
|
|
}));
|
2016-06-15 05:35:28 +02:00
|
|
|
}
|
2016-06-01 19:06:43 +02:00
|
|
|
}
|