Skip to content

Commit

Permalink
Pass errors from onClose to onError
Browse files Browse the repository at this point in the history
  • Loading branch information
Nick Clark committed Jun 17, 2019
1 parent c4f5c27 commit 837379c
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ function callbackToAsyncIterator<CallbackInput: any, ReturnVal: any>(
listener: ((arg: CallbackInput) => any) => Promise<?ReturnVal>,
options?: {
onError?: (err: Error) => void,
onClose?: (arg?: ?ReturnVal) => void,
onClose?: (arg?: ?ReturnVal) => Promise<void> | void,
buffering?: boolean,
} = {}
) {
Expand Down Expand Up @@ -54,7 +54,14 @@ function callbackToAsyncIterator<CallbackInput: any, ReturnVal: any>(
pullQueue.forEach(resolve => resolve({ value: undefined, done: true }));
pullQueue = [];
pushQueue = [];
onClose && onClose(listenerReturnValue);
if (onClose) {
try {
const closeRet = onClose(listenerReturnValue);
if (closeRet) closeRet.catch(e => onError(e));
} catch (e) {
onError(e);
}
}
}
}

Expand All @@ -66,7 +73,7 @@ function callbackToAsyncIterator<CallbackInput: any, ReturnVal: any>(
emptyQueue();
return Promise.resolve({ value: undefined, done: true });
},
throw(error) {
throw(error: Error) {
emptyQueue();
onError(error);
return Promise.reject(error);
Expand All @@ -84,7 +91,7 @@ function callbackToAsyncIterator<CallbackInput: any, ReturnVal: any>(
return() {
return Promise.reject(err);
},
throw(error) {
throw(error: Error) {
return Promise.reject(error);
},
[$$asyncIterator]() {
Expand Down
32 changes: 32 additions & 0 deletions src/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,38 @@ describe('options', () => {
});
});

it('should call onError with an error thrown by a non async onClose', async () => {
const error = new Error('Bla bla');
const listener = (cb: () => void) => Promise.resolve();

expect.assertions(1);
const iter = asyncify(listener, {
onClose: () => {
throw error;
},
onError: err => {
expect(err).toEqual(error);
},
});
await iter.return();
});

it('should call onError with an error thrown by an async onClose', async () => {
const error = new Error('Bla bla');
const listener = (cb: () => void) => Promise.resolve();

expect.assertions(1);
const iter = asyncify(listener, {
onClose: async () => {
throw error;
},
onError: err => {
expect(err).toEqual(error);
},
});
await iter.return();
});

it('should call onClose with the return value from the listener', async () => {
const returnValue = 'asdf';
const listener = (cb: () => void) =>
Expand Down

0 comments on commit 837379c

Please sign in to comment.