mapAsyncIterator.js 2.3 KB

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