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

mapAsyncIterator: allow 'rejectCallback' to only be synchronous #3012

Merged
merged 1 commit into from Apr 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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