예제 #1
0
/**
 * block waiting for the given $promise to resolve
 *
 * Once the promise is resolved, this will return whatever the promise resolves to.
 *
 * Once the promise is rejected, this will throw whatever the promise rejected with.
 *
 * If no $timeout is given and the promise stays pending, then this will
 * potentially wait/block forever until the promise is settled.
 *
 * If a $timeout is given and the promise is still pending once the timeout
 * triggers, this will cancel() the promise and throw a `TimeoutException`.
 *
 * @param PromiseInterface $promise
 * @param LoopInterface    $loop
 * @param null|float       $timeout (optional) maximum timeout in seconds or null=wait forever
 * @return mixed returns whatever the promise resolves to
 * @throws Exception when the promise is rejected
 * @throws TimeoutException if the $timeout is given and triggers
 */
function await(PromiseInterface $promise, LoopInterface $loop, $timeout = null)
{
    $wait = true;
    $resolved = null;
    $exception = null;
    if ($timeout !== null) {
        $promise = Timer\timeout($promise, $timeout, $loop);
    }
    $promise->then(function ($c) use(&$resolved, &$wait, $loop) {
        $resolved = $c;
        $wait = false;
        $loop->stop();
    }, function ($error) use(&$exception, &$wait, $loop) {
        $exception = $error;
        $wait = false;
        $loop->stop();
    });
    while ($wait) {
        $loop->run();
    }
    if ($exception !== null) {
        throw $exception;
    }
    return $resolved;
}
 public function create($host, $port)
 {
     $promise = $this->connectionManager->create($host, $port);
     return Timer\timeout($promise, $this->timeout, $this->loop)->then(null, function ($e) use($promise) {
         // connection successfully established but timeout already expired => close successful connection
         $promise->then(function ($connection) {
             $connection->end();
         });
         throw $e;
     });
 }
예제 #3
0
 public function testCancelTimeoutWillResolveIfGivenPromiseWillResolve()
 {
     $promise = new \React\Promise\Promise(function () {
     }, function ($resolve, $reject) {
         $resolve();
     });
     $timeout = Timer\timeout($promise, 0.01, $this->loop);
     $timeout->cancel();
     $this->expectPromiseResolved($promise);
     $this->expectPromiseResolved($timeout);
 }
예제 #4
0
 private function await($thenable, float $timeout = 0.1)
 {
     if (!$thenable instanceof PromiseInterface) {
         $deferred = new Deferred();
         $thenable->then([$deferred, 'resolve'], [$deferred, 'reject']);
         $thenable = $deferred->promise();
     }
     return await(timeout($thenable, $timeout, $this->eventLoop), $this->eventLoop);
 }