Skip to content

Commit 50dcfaa

Browse files
committed
mapAsyncIterator: refactor async iterator
1 parent 2673bdf commit 50dcfaa

File tree

1 file changed

+23
-28
lines changed

1 file changed

+23
-28
lines changed

src/subscription/mapAsyncIterator.js

Lines changed: 23 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -11,45 +11,40 @@ export function mapAsyncIterator<T, U>(
1111
// $FlowIssue[incompatible-use]
1212
const iterator = iterable[Symbol.asyncIterator]();
1313

14-
async function abruptClose(error: mixed) {
15-
if (typeof iterator.return === 'function') {
16-
try {
17-
await iterator.return();
18-
} catch (_e) {
19-
/* ignore error */
20-
}
14+
async function mapResult(
15+
result: IteratorResult<T, void>,
16+
): Promise<IteratorResult<U, void>> {
17+
if (result.done) {
18+
return result;
2119
}
22-
throw error;
23-
}
2420

25-
async function mapResult(resultPromise: Promise<IteratorResult<T, void>>) {
2621
try {
27-
const result = await resultPromise;
28-
29-
if (result.done) {
30-
return result;
31-
}
32-
3322
return { value: await callback(result.value), done: false };
34-
} catch (callbackError) {
35-
return abruptClose(callbackError);
23+
} catch (error) {
24+
if (typeof iterator.return === 'function') {
25+
try {
26+
await iterator.return();
27+
} catch (_e) {
28+
/* ignore error */
29+
}
30+
}
31+
throw error;
3632
}
3733
}
3834

3935
return {
40-
next(): Promise<IteratorResult<U, void>> {
41-
return mapResult(iterator.next());
36+
async next() {
37+
return mapResult(await iterator.next());
4238
},
43-
return(): Promise<IteratorResult<U, void>> {
39+
async return(): Promise<IteratorResult<U, void>> {
4440
return typeof iterator.return === 'function'
45-
? mapResult(iterator.return())
46-
: Promise.resolve({ value: undefined, done: true });
41+
? mapResult(await iterator.return())
42+
: { value: undefined, done: true };
4743
},
48-
throw(error?: mixed): Promise<IteratorResult<U, void>> {
49-
if (typeof iterator.throw === 'function') {
50-
return mapResult(iterator.throw(error));
51-
}
52-
return Promise.reject(error).catch(abruptClose);
44+
async throw(error?: mixed) {
45+
return typeof iterator.throw === 'function'
46+
? mapResult(await iterator.throw(error))
47+
: Promise.reject(error);
5348
},
5449
[Symbol.asyncIterator]() {
5550
return this;

0 commit comments

Comments
 (0)