mirror of
https://github.com/danog/amp.git
synced 2024-11-30 04:29:08 +01:00
Add timeout() function
This commit is contained in:
parent
905d5bfc2c
commit
34088cbf52
@ -423,6 +423,43 @@ function pipe($promise, callable $functor) {
|
||||
return $promisor->promise();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an artificial timeout for any Promise instance
|
||||
*
|
||||
* If the timeout expires prior to promise resolution the returned
|
||||
* promise is failed.
|
||||
*
|
||||
* @param \Amp\Promise $promise The promise to which the timeout applies
|
||||
* @param int $msTimeout The timeout in milliseconds
|
||||
* @param \Amp\Reactor $reactor Optional reactor instance -- defaults to the global reactor
|
||||
* @return \Amp\Promise
|
||||
*/
|
||||
function timeout(Promise $promise, $msTimeout, Reactor $reactor = null) {
|
||||
$reactor = $reactor ?: reactor();
|
||||
$resolved = false;
|
||||
$promisor = new Deferred;
|
||||
$watcherId = $reactor->once(function() use ($promisor, &$resolved) {
|
||||
$resolved = true;
|
||||
$promisor->fail(new \RuntimeException(
|
||||
"Promise resolution timed out"
|
||||
));
|
||||
}, $msTimeout);
|
||||
$promise->when(function($error = null, $result = null) use ($reactor, $promisor, $watcherId, $resolved) {
|
||||
if ($resolved) {
|
||||
return;
|
||||
}
|
||||
|
||||
$reactor->cancel($watcherId);
|
||||
if ($error) {
|
||||
$promisor->fail($error);
|
||||
} else {
|
||||
$promisor->succeed($result);
|
||||
}
|
||||
});
|
||||
|
||||
return $promisor->promise();
|
||||
}
|
||||
|
||||
/**
|
||||
* Block script execution indefinitely until the specified Promise resolves
|
||||
*
|
||||
|
@ -162,6 +162,17 @@ class FunctionsTest extends \PHPUnit_Framework_TestCase {
|
||||
$this->assertSame(1, $invoked);
|
||||
}
|
||||
|
||||
/**
|
||||
* @expectedException \RuntimeException
|
||||
* @expectedExceptionMessage Promise resolution timed out
|
||||
*/
|
||||
public function testTimeout() {
|
||||
(new NativeReactor)->run(function($reactor) use (&$invoked) {
|
||||
$pause = new \Amp\Pause(1000, $reactor);
|
||||
yield \Amp\timeout($pause, 10, $reactor);
|
||||
});
|
||||
}
|
||||
|
||||
public function testAllCombinatorResolution() {
|
||||
$invoked = 0;
|
||||
(new NativeReactor)->run(function($reactor) use (&$invoked) {
|
||||
|
Loading…
Reference in New Issue
Block a user