Skip to content

Commit

Permalink
Ensure onClose is only called once we receive a value from the listener
Browse files Browse the repository at this point in the history
  • Loading branch information
Nick Clark committed Jun 17, 2019
1 parent 837379c commit 0d672b5
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,14 @@ function callbackToAsyncIterator<CallbackInput: any, ReturnVal: any>(
let pushQueue = [];
let listening = true;
let listenerReturnValue;
let listenerReturnedValue = false;
let closingWaitingOnListenerReturnValue = false;
// Start listener
listener(value => pushValue(value))
.then(a => {
listenerReturnValue = a;
listenerReturnedValue = true;
if (closingWaitingOnListenerReturnValue) emptyQueue();
})
.catch(err => {
onError(err);
Expand All @@ -49,6 +53,10 @@ function callbackToAsyncIterator<CallbackInput: any, ReturnVal: any>(
}

function emptyQueue() {
if (onClose && !listenerReturnedValue) {
closingWaitingOnListenerReturnValue = true;
return;
}
if (listening) {
listening = false;
pullQueue.forEach(resolve => resolve({ value: undefined, done: true }));
Expand Down
18 changes: 18 additions & 0 deletions src/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,24 @@ describe('options', () => {
await iter.return();
});

it('should call onClose with the return value from an listener only after the promise resolves', async () => {
const returnValue = 'asdf';
const listener = (cb: () => void) =>
new Promise(res => {
res(returnValue);
});

expect.hasAssertions();
const iter = asyncify(listener, {
onClose: val => {
expect(val).toEqual(returnValue);
},
});
// Wait a tick so that the promise resolves with the return value
iter.return();
await new Promise(res => setTimeout(res, 10));
});

describe('buffering', () => {
it('should not buffer incoming values if disabled', async () => {
const listener = (cb: (arg: number) => void) =>
Expand Down

0 comments on commit 0d672b5

Please sign in to comment.