mapAsyncIterator.mjs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  2. import { $$asyncIterator, getAsyncIterator } from 'iterall';
  3. /**
  4. * Given an AsyncIterable and a callback function, return an AsyncIterator
  5. * which produces values mapped via calling the callback function.
  6. */
  7. export default function mapAsyncIterator(iterable, callback, rejectCallback) {
  8. var iterator = getAsyncIterator(iterable);
  9. var $return;
  10. var abruptClose; // $FlowFixMe(>=0.68.0)
  11. if (typeof iterator.return === 'function') {
  12. $return = iterator.return;
  13. abruptClose = function abruptClose(error) {
  14. var rethrow = function rethrow() {
  15. return Promise.reject(error);
  16. };
  17. return $return.call(iterator).then(rethrow, rethrow);
  18. };
  19. }
  20. function mapResult(result) {
  21. return result.done ? result : asyncMapValue(result.value, callback).then(iteratorResult, abruptClose);
  22. }
  23. var mapReject;
  24. if (rejectCallback) {
  25. // Capture rejectCallback to ensure it cannot be null.
  26. var reject = rejectCallback;
  27. mapReject = function mapReject(error) {
  28. return asyncMapValue(error, reject).then(iteratorResult, abruptClose);
  29. };
  30. }
  31. /* TODO: Flow doesn't support symbols as keys:
  32. https://github.com/facebook/flow/issues/3258 */
  33. return _defineProperty({
  34. next: function next() {
  35. return iterator.next().then(mapResult, mapReject);
  36. },
  37. return: function _return() {
  38. return $return ? $return.call(iterator).then(mapResult, mapReject) : Promise.resolve({
  39. value: undefined,
  40. done: true
  41. });
  42. },
  43. throw: function _throw(error) {
  44. // $FlowFixMe(>=0.68.0)
  45. if (typeof iterator.throw === 'function') {
  46. return iterator.throw(error).then(mapResult, mapReject);
  47. }
  48. return Promise.reject(error).catch(abruptClose);
  49. }
  50. }, $$asyncIterator, function () {
  51. return this;
  52. });
  53. }
  54. function asyncMapValue(value, callback) {
  55. return new Promise(function (resolve) {
  56. return resolve(callback(value));
  57. });
  58. }
  59. function iteratorResult(value) {
  60. return {
  61. value: value,
  62. done: false
  63. };
  64. }