1
0
mirror of https://github.com/danog/amp.git synced 2024-11-30 04:29:08 +01:00

Normalize coroutine() return to Promise type

This commit is contained in:
Daniel Lowrey 2015-08-07 10:41:14 -04:00
parent ad4831888f
commit 5cad406795
2 changed files with 31 additions and 1 deletions

View File

@ -734,7 +734,13 @@ function wait(Promise $promise) {
function coroutine(callable $func) {
return function () use ($func) {
$out = \call_user_func_array($func, \func_get_args());
return ($out instanceof \Generator) ? resolve($out) : $out;
if ($out instanceof \Generator) {
return resolve($out);
} elseif ($out instanceof Promise) {
return $out;
} else {
return new Success($out);
}
};
}

View File

@ -671,6 +671,30 @@ class FunctionsTest extends \PHPUnit_Framework_TestCase {
$this->assertSame(1, $invoked);
}
public function testCoroutineWrapsNonGeneratorReturnInPromise() {
$co = \Amp\coroutine(function () {
return 42;
});
$out = $co();
$this->assertInstanceOf("\Amp\Success", $out);
$invoked = false;
$out->when(function ($error, $result) use (&$invoked) {
$this->assertNull($error);
$this->assertSame(42, $result);
$invoked = true;
});
$this->assertTrue($invoked);
}
public function testCoroutineReturnsPromiseResultUnmodified() {
$success = new \Amp\Success;
$co = \Amp\coroutine(function () use ($success) {
return $success;
});
$out = $co();
$this->assertSame($success, $out);
}
public function testNestedCoroutineResolutionContinuation() {
$invoked = 0;
\Amp\run(function () use (&$invoked) {