Skip to content
This repository has been archived by the owner on Oct 11, 2022. It is now read-only.

Fix onClose #27

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
Prev Previous commit
Ensure onClose is only called once we receive a value from the listener
Nick Clark committed Jun 17, 2019
commit 0d672b5b6ed3f1f3491cdcd981391a95d78f1d6c
8 changes: 8 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -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);
@@ -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 }));
18 changes: 18 additions & 0 deletions src/test/index.test.js
Original file line number Diff line number Diff line change
@@ -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) =>