_async_generator.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = AsyncGenerator;
  6. var _awaitValueMjs = _interopRequireDefault(require("./_await_value.js"));
  7. function AsyncGenerator(gen) {
  8. var front, back;
  9. function send(key, arg) {
  10. return new Promise(function(resolve, reject) {
  11. var request = {
  12. key: key,
  13. arg: arg,
  14. resolve: resolve,
  15. reject: reject,
  16. next: null
  17. };
  18. if (back) {
  19. back = back.next = request;
  20. } else {
  21. front = back = request;
  22. resume(key, arg);
  23. }
  24. });
  25. }
  26. function resume(key, arg1) {
  27. try {
  28. var result = gen[key](arg1);
  29. var value = result.value;
  30. var wrappedAwait = value instanceof _awaitValueMjs.default;
  31. Promise.resolve(wrappedAwait ? value.wrapped : value).then(function(arg) {
  32. if (wrappedAwait) {
  33. resume("next", arg);
  34. return;
  35. }
  36. settle(result.done ? "return" : "normal", arg);
  37. }, function(err) {
  38. resume("throw", err);
  39. });
  40. } catch (err) {
  41. settle("throw", err);
  42. }
  43. }
  44. function settle(type, value) {
  45. switch(type){
  46. case "return":
  47. front.resolve({
  48. value: value,
  49. done: true
  50. });
  51. break;
  52. case "throw":
  53. front.reject(value);
  54. break;
  55. default:
  56. front.resolve({
  57. value: value,
  58. done: false
  59. });
  60. break;
  61. }
  62. front = front.next;
  63. if (front) {
  64. resume(front.key, front.arg);
  65. } else {
  66. back = null;
  67. }
  68. }
  69. this._invoke = send;
  70. if (typeof gen.return !== "function") {
  71. this.return = undefined;
  72. }
  73. }
  74. function _interopRequireDefault(obj) {
  75. return obj && obj.__esModule ? obj : {
  76. default: obj
  77. };
  78. }
  79. if (typeof Symbol === "function" && Symbol.asyncIterator) {
  80. AsyncGenerator.prototype[Symbol.asyncIterator] = function() {
  81. return this;
  82. };
  83. }
  84. AsyncGenerator.prototype.next = function(arg) {
  85. return this._invoke("next", arg);
  86. };
  87. AsyncGenerator.prototype.throw = function(arg) {
  88. return this._invoke("throw", arg);
  89. };
  90. AsyncGenerator.prototype.return = function(arg) {
  91. return this._invoke("return", arg);
  92. };