Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reject first() when stream emits an error event #7

Merged
merged 1 commit into from
Nov 28, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
7 changes: 7 additions & 0 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'));
Expand Down
4 changes: 2 additions & 2 deletions tests/FirstTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down