mapAsyncIterator.js.flow 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // @flow strict
  2. import { $$asyncIterator, getAsyncIterator } from 'iterall';
  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. const iterator = getAsyncIterator(iterable);
  14. let $return;
  15. let abruptClose;
  16. // $FlowFixMe(>=0.68.0)
  17. if (typeof iterator.return === 'function') {
  18. $return = iterator.return;
  19. abruptClose = error => {
  20. const rethrow = () => Promise.reject(error);
  21. return $return.call(iterator).then(rethrow, rethrow);
  22. };
  23. }
  24. function mapResult(result) {
  25. return result.done
  26. ? result
  27. : asyncMapValue(result.value, callback).then(iteratorResult, abruptClose);
  28. }
  29. let mapReject;
  30. if (rejectCallback) {
  31. // Capture rejectCallback to ensure it cannot be null.
  32. const reject = rejectCallback;
  33. mapReject = error =>
  34. asyncMapValue(error, reject).then(iteratorResult, abruptClose);
  35. }
  36. /* TODO: Flow doesn't support symbols as keys:
  37. https://github.com/facebook/flow/issues/3258 */
  38. return ({
  39. next() {
  40. return iterator.next().then(mapResult, mapReject);
  41. },
  42. return() {
  43. return $return
  44. ? $return.call(iterator).then(mapResult, mapReject)
  45. : Promise.resolve({ value: undefined, done: true });
  46. },
  47. throw(error) {
  48. // $FlowFixMe(>=0.68.0)
  49. if (typeof iterator.throw === 'function') {
  50. return iterator.throw(error).then(mapResult, mapReject);
  51. }
  52. return Promise.reject(error).catch(abruptClose);
  53. },
  54. [$$asyncIterator]() {
  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. }