From 00334dcc693285877a479490baba508f56d894fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20L=C3=BCck?= Date: Tue, 28 Nov 2017 11:31:15 +0100 Subject: [PATCH] Reject first() when stream emits an error event --- README.md | 3 +++ src/functions.php | 7 +++++++ tests/FirstTest.php | 4 ++-- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 770fc47..b25a71f 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,9 @@ event does not pass any data. If you do not pass a custom event name, then it will wait for the first "data" event and resolve with a string containing the first data chunk. +The promise will reject if the stream emits an error – unless you're waiting for +the "error" event, in which case it will resolve. + The promise will reject once the stream closes – unless you're waiting for the "close" event, in which case it will resolve. diff --git a/src/functions.php b/src/functions.php index 24c250d..30e2129 100644 --- a/src/functions.php +++ b/src/functions.php @@ -84,6 +84,13 @@ function first(EventEmitterInterface $stream, $event = 'data') }; $stream->on($event, $listener); + if ($event !== 'error') { + $stream->on('error', function ($error) use ($stream, $event, $listener, $reject) { + $stream->removeListener($event, $listener); + $reject(new \RuntimeException('An error occured on the underlying stream while waiting for event', 0, $error)); + }); + } + $stream->on('close', function () use ($stream, $event, $listener, $reject) { $stream->removeListener($event, $listener); $reject(new \RuntimeException('Stream closed')); diff --git a/tests/FirstTest.php b/tests/FirstTest.php index fdfa0d3..31b728b 100644 --- a/tests/FirstTest.php +++ b/tests/FirstTest.php @@ -76,14 +76,14 @@ public function testEmittingDataOnStreamResolvesWithFirstEvent() $this->expectPromiseResolveWith('hello', $promise); } - public function testEmittingErrorOnStreamDoesNothing() + public function testEmittingErrorOnStreamWillReject() { $stream = new ThroughStream(); $promise = Stream\first($stream); $stream->emit('error', array(new \RuntimeException('test'))); - $promise->then($this->expectCallableNever(), $this->expectCallableNever()); + $this->expectPromiseReject($promise); } public function testEmittingErrorResolvesWhenWaitingForErrorEvent()