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

Make iterators AsyncIterable, Closes #89 #102

Merged
merged 6 commits into from
Feb 16, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
7 changes: 6 additions & 1 deletion asynciterator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,11 @@ export class AsyncIterator<T> extends EventEmitter implements AsyncIterable<T> {
/**
* An AsyncIterator is async iterable.
* This allows iterators to be used via the for-await syntax.
*
* In cases where the returned EcmaScript AsyncIterator will not be fully consumed,
* it is recommended to manually listen for error events on the main AsyncIterator
* to avoid uncaught error messages.
*
* @returns {ESAsyncIterator<T>} An EcmaScript AsyncIterator
*/
[Symbol.asyncIterator](): ESAsyncIterator<T> {
Expand Down Expand Up @@ -611,7 +616,7 @@ export class AsyncIterator<T> extends EventEmitter implements AsyncIterable<T> {
currentResolve = currentReject = pendingError = null;
removeListeners();
}
else if (pendingError !== null) {
else if (pendingError === null) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤦 obvs I put that in on purpose to check your tests

pendingError = error;
}
}
Expand Down
34 changes: 34 additions & 0 deletions test/AsyncIterator-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1415,6 +1415,40 @@ describe('AsyncIterator', () => {
caughtError.message.should.eql('AsyncIterator error');
});
});

describe('called on an iterator that errors inbetween next() calls', () => {
let iterator;
before(() => {
let i = 0;
iterator = new AsyncIterator();
iterator.readable = true;
iterator.read = () => {
if (i++ < 2)
return i;
return null;
};
});

it('should throw errors that were emitted before next() was called', async () => {
const values = [];
let caughtError;
const esit = iterator[Symbol.asyncIterator]();

values.push(await esit.next());

iterator.emit('error', new Error('AsyncIterator error'));

try {
await esit.next();
}
catch (error) {
caughtError = error;
}

values.should.eql([{ done: false, value: 1 }]);
caughtError.message.should.eql('AsyncIterator error');
});
});
});
});

Expand Down