mirror of
https://github.com/danog/amp.git
synced 2024-11-26 20:15:00 +01:00
Document yield vs yield from (#226)
This commit is contained in:
parent
fa3fe1d20b
commit
81e7024e14
@ -44,3 +44,59 @@ All `yield`s in a coroutine must be one of the following three types:
|
||||
| `Amp\Promise` | Any promise instance may be yielded and control will be returned to the coroutine once the promise resolves. If resolution fails the relevant exception is thrown into the generator and must be handled by the application or it will bubble up. If resolution succeeds the promise's resolved value is sent back into the generator. |
|
||||
| `React\Promise\PromiseInterface` | Same as `Amp\Promise`. Any React promise will automatically be adapted to an Amp promise. |
|
||||
| `array` | Yielding an array of promises combines them implicitly using `Amp\Promise\all()`. An array with elements not being promises will result in an `Amp\InvalidYieldError`. |
|
||||
|
||||
## Yield VS Yield From
|
||||
|
||||
Yield is used to "await" promises, yield from can be used to delegate to a sub-routine. Yield from should only be used to delegate to private methods, any public API should always return promises instead of generators.
|
||||
|
||||
Yield promises from within a `\Generator`, the code within the `\Generator` will continue, as soon as the promise is resolved. Use `yield from` to yield the result of a `\Generator`. Instead of using yield from, you can also use `yield new Coroutine($this->bar());` or `yield call([$this, "bar"]);`.
|
||||
|
||||
An example:
|
||||
|
||||
```php
|
||||
class Foo
|
||||
{
|
||||
public function delegationWithCoroutine(): Amp\Promise
|
||||
{
|
||||
return new Amp\Coroutine($this->bar());
|
||||
}
|
||||
|
||||
public function delegationWithYieldFrom(): Amp\Promise
|
||||
{
|
||||
return Amp\call(function () {
|
||||
return yield from $this->bar();
|
||||
});
|
||||
}
|
||||
|
||||
public function delegationWithCallable(): Amp\Promise
|
||||
{
|
||||
return Amp\call([$this, 'bar']);
|
||||
}
|
||||
|
||||
public function bar(): Generator
|
||||
{
|
||||
yield new Amp\Success(1);
|
||||
yield new Amp\Success(2);
|
||||
return yield new Amp\Success(3);
|
||||
}
|
||||
}
|
||||
|
||||
Amp\Loop::run(function () {
|
||||
$foo = new Foo();
|
||||
$r1 = yield $foo->delegationWithCoroutine();
|
||||
$r2 = yield $foo->delegationWithYieldFrom();
|
||||
$r3 = yield $foo->delegationWithCallable();
|
||||
var_dump($r1);
|
||||
var_dump($r2);
|
||||
var_dump($r3);
|
||||
});
|
||||
```
|
||||
|
||||
Outputs:
|
||||
```
|
||||
int(3)
|
||||
int(3)
|
||||
int(3)
|
||||
```
|
||||
|
||||
For further information about the "yield from" keyword, see [PHP Manual](http://php.net/manual/en/language.generators.syntax.php#control-structures.yield.from)
|
||||
|
Loading…
Reference in New Issue
Block a user