mapAsyncIterator.js 2.3 KB

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