mapAsyncIterator.mjs 2.2 KB

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