Skip to content

Commit

Permalink
mapAsyncIterator: allow 'rejectCallback' to only be synchronous (#3012)
Browse files Browse the repository at this point in the history
  • Loading branch information
IvanGoncharov committed Apr 2, 2021
1 parent 0f3e91f commit 6c53a27
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 19 deletions.
22 changes: 8 additions & 14 deletions src/subscription/__tests__/mapAsyncIterator-test.js
Expand Up @@ -354,13 +354,19 @@ describe('mapAsyncIterator', () => {
);
});

async function testClosesSourceWithRejectMapper<T>(mapper: (Error) => T) {
it('closes source if mapper throws an error', async () => {
async function* source() {
yield 1;
throw new Error(2);
}

const throwOver1 = mapAsyncIterator(source(), (x) => x, mapper);
const throwOver1 = mapAsyncIterator(
source(),
(x) => x,
(error) => {
throw new Error('Cannot count to ' + error.message);
},
);

expect(await throwOver1.next()).to.deep.equal({ value: 1, done: false });

Expand All @@ -379,17 +385,5 @@ describe('mapAsyncIterator', () => {
value: undefined,
done: true,
});
}

it('closes source if mapper throws an error', async () => {
await testClosesSourceWithRejectMapper((error) => {
throw new Error('Cannot count to ' + error.message);
});
});

it('closes source if mapper rejects', async () => {
await testClosesSourceWithRejectMapper((error) =>
Promise.reject(new Error('Cannot count to ' + error.message)),
);
});
});
11 changes: 6 additions & 5 deletions src/subscription/mapAsyncIterator.js
Expand Up @@ -7,7 +7,7 @@ import type { PromiseOrValue } from '../jsutils/PromiseOrValue';
export function mapAsyncIterator<T, U>(
iterable: AsyncIterable<T> | AsyncGenerator<T, void, void>,
callback: (T) => PromiseOrValue<U>,
rejectCallback: (any) => PromiseOrValue<U> = (error) => {
rejectCallback: (any) => U = (error) => {
throw error;
},
): AsyncGenerator<U, void, void> {
Expand All @@ -31,10 +31,11 @@ export function mapAsyncIterator<T, U>(
}

function mapReject(error: mixed) {
return asyncMapValue(error, rejectCallback).then(
iteratorResult,
abruptClose,
);
try {
return { value: rejectCallback(error), done: false };
} catch (callbackError) {
return abruptClose(callbackError);
}
}

/* TODO: Flow doesn't support symbols as keys:
Expand Down

0 comments on commit 6c53a27

Please sign in to comment.