Пример #1
0
 /**
  * @param int $time Milliseconds before succeeding the promise.
  * @param mixed $value Succeed the promise with this value.
  */
 public function __construct(int $time, $value = null)
 {
     Loop::delay($time, function () use($value) {
         $this->resolve($value);
     });
 }
Пример #2
0
/**
 * Create an artificial timeout for any Promise.
 *
 * If the timeout expires before the promise is resolved, the returned promise fails with an instance of
 * \Amp\TimeoutException.
 *
 * @param \Interop\Async\Promise $promise
 * @param int $timeout Timeout in milliseconds.
 *
 * @return \Interop\Async\Promise
 */
function timeout(Promise $promise, int $timeout) : Promise
{
    $deferred = new Deferred();
    $resolved = false;
    $watcher = Loop::delay($timeout, function () use(&$resolved, $deferred) {
        if (!$resolved) {
            $resolved = true;
            $deferred->fail(new TimeoutException());
        }
    });
    $promise->when(function () use(&$resolved, $promise, $deferred, $watcher) {
        Loop::cancel($watcher);
        if ($resolved) {
            return;
        }
        $resolved = true;
        $deferred->resolve($promise);
    });
    return $deferred->promise();
}