amphp / amp

A non-blocking concurrency framework for PHP applications. 🐘

Home Page:https://amphp.org/amp

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

A concise way of resolving results that may turn out to be Promise, Generator or something else

razshare opened this issue · comments

First of all thanks for the great work.


I have a feeling this might be a stupid question, but here I go.

How would you go on about resolving the result of a function/method that returns :Promise|ReactPromise|Generator|SomeOtherType without doing this

$result = myFunction();  //may return a Promise, Generator or something else
if($result instanceof \Generator)
	yield from $result;
if($result instanceof \Amp\Promise)
	yield $result;
if($result instanceof \React\Promise\PromiseInterface)
	yield \Amp\Promise\adapt($result);

\Amp\call is so close to solving this yet so far and \Amp\Coroutine takes only Generators.
Am I missing something or is that the only way?

Or maybe this a practice that's discouraged?

You can use Amp\call for this: Amp\call(myFunction(...)).

But it takes a callable, no?

function call(callable $callback, ...$args): Promise

It throws the following using a generator:

Uncaught TypeError: Amp\call(): Argument #1 ($callback) must be of type callable, Generator given

Yes, (...) is PHP 8.1's first class callable syntax, not an omission. If you already have a value, you can also use Amp\call(fn () => $value).

Yes, (...) is PHP 8.1's first class callable syntax

I see, that does it.

Thanks a lot!