1
0
mirror of https://github.com/danog/amp.git synced 2025-01-23 05:41:25 +01:00
amp/lib/Coroutine.php

46 lines
1.4 KiB
PHP
Raw Normal View History

<?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
/**
* @deprecated Use {@see await()} and ext-fiber to await promises.
*
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.
*
* @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
{
2016-05-21 09:44:52 -05:00
use Internal\Placeholder;
/**
* @param \Generator $generator
* @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)
{
$this->resolve(async(function () use ($generator): mixed {
$yielded = $generator->current();
while ($generator->valid()) {
2019-05-20 20:29:09 +02:00
try {
$value = await($yielded);
2019-05-20 20:29:09 +02:00
} catch (\Throwable $exception) {
$yielded = $generator->throw($exception);
continue;
}
2016-05-21 09:44:52 -05:00
$yielded = $generator->send($value);
}
return $generator->getReturn();
}));
}
2016-06-01 12:06:43 -05:00
}