mapAsyncIterator.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true,
  4. });
  5. exports.mapAsyncIterator = mapAsyncIterator;
  6. /**
  7. * Given an AsyncIterable and a callback function, return an AsyncIterator
  8. * which produces values mapped via calling the callback function.
  9. */
  10. function mapAsyncIterator(iterable, callback) {
  11. const iterator = iterable[Symbol.asyncIterator]();
  12. async function mapResult(result) {
  13. if (result.done) {
  14. return result;
  15. }
  16. try {
  17. return {
  18. value: await callback(result.value),
  19. done: false,
  20. };
  21. } catch (error) {
  22. /* c8 ignore start */
  23. // FIXME: add test case
  24. if (typeof iterator.return === 'function') {
  25. try {
  26. await iterator.return();
  27. } catch (_e) {
  28. /* ignore error */
  29. }
  30. }
  31. throw error;
  32. /* c8 ignore stop */
  33. }
  34. }
  35. return {
  36. async next() {
  37. return mapResult(await iterator.next());
  38. },
  39. async return() {
  40. // If iterator.return() does not exist, then type R must be undefined.
  41. return typeof iterator.return === 'function'
  42. ? mapResult(await iterator.return())
  43. : {
  44. value: undefined,
  45. done: true,
  46. };
  47. },
  48. async throw(error) {
  49. if (typeof iterator.throw === 'function') {
  50. return mapResult(await iterator.throw(error));
  51. }
  52. throw error;
  53. },
  54. [Symbol.asyncIterator]() {
  55. return this;
  56. },
  57. };
  58. }