Пример #1
0
 public function parsePlainStream(PromiseInterface $promise)
 {
     // text/plain
     $out = new ReadableStream();
     // try to cancel promise once the stream closes
     if ($promise instanceof CancellablePromiseInterface) {
         $out->on('close', function () use($promise) {
             $promise->cancel();
         });
     }
     $promise->then(function ($response) use($out) {
         $out->close();
     }, function ($error) use($out) {
         $out->emit('error', array($error, $out));
         $out->close();
     }, function ($progress) use($out) {
         if (is_array($progress) && isset($progress['responseStream'])) {
             $stream = $progress['responseStream'];
             /* @var $stream React\Stream\Stream */
             // hack to do not buffer stream contents in body
             $stream->removeAllListeners('data');
             // got a streaming HTTP response => forward each data chunk to the resulting output stream
             $stream->on('data', function ($data) use($out) {
                 $out->emit('data', array($data, $out));
             });
         }
     });
     return $out;
 }
Пример #2
0
function timeout(PromiseInterface $promise, $time, LoopInterface $loop)
{
    // cancelling this promise will only try to cancel the input promise,
    // thus leaving responsibility to the input promise.
    $canceller = null;
    if ($promise instanceof CancellablePromiseInterface) {
        $canceller = array($promise, 'cancel');
    }
    return new Promise(function ($resolve, $reject) use($loop, $time, $promise) {
        $timer = $loop->addTimer($time, function () use($time, $promise, $reject) {
            $reject(new TimeoutException($time, 'Timed out after ' . $time . ' seconds'));
            if ($promise instanceof CancellablePromiseInterface) {
                $promise->cancel();
            }
        });
        $promise->then(function ($v) use($timer, $loop, $resolve) {
            $loop->cancelTimer($timer);
            $resolve($v);
        }, function ($v) use($timer, $loop, $reject) {
            $loop->cancelTimer($timer);
            $reject($v);
        });
    }, $canceller);
}