When a promise is yielded, execution of the generator is interrupted until the promise is resolved. A success
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.
/** * @param callable(callable(mixed $value): Promise $emit): \Generator $emitter * * @throws \Error Thrown if the callable does not return a Generator. */ public function __construct(callable $emitter) { $result = $emitter($this->callableFromInstanceMethod("emit")); if (!$result instanceof \Generator) { throw new \Error("The callable did not return a Generator"); } Loop::defer(function () use($result) { $coroutine = new Coroutine($result); $coroutine->when(function ($exception, $value) { if ($this->resolved) { return; } if ($exception) { $this->fail($exception); return; } $this->resolve($value); }); }); }