mapAsyncIterator.js.flow 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // @flow strict
  2. import { SYMBOL_ASYNC_ITERATOR } from '../polyfills/symbols';
  3. import type { PromiseOrValue } from '../jsutils/PromiseOrValue';
  4. /**
  5. * Given an AsyncIterable and a callback function, return an AsyncIterator
  6. * which produces values mapped via calling the callback function.
  7. */
  8. export default function mapAsyncIterator<T, U>(
  9. iterable: AsyncIterable<T> | AsyncGenerator<T, void, void>,
  10. callback: (T) => PromiseOrValue<U>,
  11. rejectCallback?: (any) => PromiseOrValue<U>,
  12. ): AsyncGenerator<U, void, void> {
  13. // $FlowFixMe[prop-missing]
  14. const iteratorMethod = iterable[SYMBOL_ASYNC_ITERATOR];
  15. const iterator: any = iteratorMethod.call(iterable);
  16. let $return: any;
  17. let abruptClose;
  18. if (typeof iterator.return === 'function') {
  19. $return = iterator.return;
  20. abruptClose = (error: mixed) => {
  21. const rethrow = () => Promise.reject(error);
  22. return $return.call(iterator).then(rethrow, rethrow);
  23. };
  24. }
  25. function mapResult(result: IteratorResult<T, void>) {
  26. return result.done
  27. ? result
  28. : asyncMapValue(result.value, callback).then(iteratorResult, abruptClose);
  29. }
  30. let mapReject;
  31. if (rejectCallback) {
  32. // Capture rejectCallback to ensure it cannot be null.
  33. const reject = rejectCallback;
  34. mapReject = (error: mixed) =>
  35. asyncMapValue(error, reject).then(iteratorResult, abruptClose);
  36. }
  37. /* TODO: Flow doesn't support symbols as keys:
  38. https://github.com/facebook/flow/issues/3258 */
  39. return ({
  40. next(): Promise<IteratorResult<U, void>> {
  41. return iterator.next().then(mapResult, mapReject);
  42. },
  43. return() {
  44. return $return
  45. ? $return.call(iterator).then(mapResult, mapReject)
  46. : Promise.resolve({ value: undefined, done: true });
  47. },
  48. throw(error?: mixed): Promise<IteratorResult<U, void>> {
  49. if (typeof iterator.throw === 'function') {
  50. return iterator.throw(error).then(mapResult, mapReject);
  51. }
  52. return Promise.reject(error).catch(abruptClose);
  53. },
  54. [SYMBOL_ASYNC_ITERATOR]() {
  55. return this;
  56. },
  57. }: $FlowFixMe);
  58. }
  59. function asyncMapValue<T, U>(
  60. value: T,
  61. callback: (T) => PromiseOrValue<U>,
  62. ): Promise<U> {
  63. return new Promise((resolve) => resolve(callback(value)));
  64. }
  65. function iteratorResult<T>(value: T): IteratorResult<T, void> {
  66. return { value, done: false };
  67. }