123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- import { $$asyncIterator, getAsyncIterator } from 'iterall';
- import { type PromiseOrValue } from '../jsutils/PromiseOrValue';
- export default function mapAsyncIterator<T, U>(
- iterable: AsyncIterable<T>,
- callback: T => PromiseOrValue<U>,
- rejectCallback?: any => PromiseOrValue<U>,
- ): AsyncGenerator<U, void, void> {
- const iterator = getAsyncIterator(iterable);
- let $return;
- let abruptClose;
-
- if (typeof iterator.return === 'function') {
- $return = iterator.return;
- abruptClose = error => {
- const rethrow = () => Promise.reject(error);
- return $return.call(iterator).then(rethrow, rethrow);
- };
- }
- function mapResult(result) {
- return result.done
- ? result
- : asyncMapValue(result.value, callback).then(iteratorResult, abruptClose);
- }
- let mapReject;
- if (rejectCallback) {
-
- const reject = rejectCallback;
- mapReject = error =>
- asyncMapValue(error, reject).then(iteratorResult, abruptClose);
- }
-
- return ({
- next() {
- return iterator.next().then(mapResult, mapReject);
- },
- return() {
- return $return
- ? $return.call(iterator).then(mapResult, mapReject)
- : Promise.resolve({ value: undefined, done: true });
- },
- throw(error) {
-
- if (typeof iterator.throw === 'function') {
- return iterator.throw(error).then(mapResult, mapReject);
- }
- return Promise.reject(error).catch(abruptClose);
- },
- [$$asyncIterator]() {
- return this;
- },
- }: any);
- }
- function asyncMapValue<T, U>(
- value: T,
- callback: T => PromiseOrValue<U>,
- ): Promise<U> {
- return new Promise(resolve => resolve(callback(value)));
- }
- function iteratorResult<T>(value: T): IteratorResult<T, void> {
- return { value, done: false };
- }
|