mapAsyncIterator.js.flow 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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>,
  10. callback: (T) => PromiseOrValue<U>,
  11. rejectCallback?: (any) => PromiseOrValue<U>,
  12. ): AsyncGenerator<U, void, void> {
  13. // $FlowFixMe
  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) => {
  21. const rethrow = () => Promise.reject(error);
  22. return $return.call(iterator).then(rethrow, rethrow);
  23. };
  24. }
  25. function mapResult(result) {
  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) =>
  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() {
  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) {
  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. }: any);
  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. }