AsyncGenerator.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. var OverloadYield = require("./OverloadYield.js");
  2. function AsyncGenerator(gen) {
  3. var front, back;
  4. function resume(key, arg) {
  5. try {
  6. var result = gen[key](arg),
  7. value = result.value,
  8. overloaded = value instanceof OverloadYield;
  9. Promise.resolve(overloaded ? value.v : value).then(function (arg) {
  10. if (overloaded) {
  11. var nextKey = "return" === key ? "return" : "next";
  12. if (!value.k || arg.done) return resume(nextKey, arg);
  13. arg = gen[nextKey](arg).value;
  14. }
  15. settle(result.done ? "return" : "normal", arg);
  16. }, function (err) {
  17. resume("throw", err);
  18. });
  19. } catch (err) {
  20. settle("throw", err);
  21. }
  22. }
  23. function settle(type, value) {
  24. switch (type) {
  25. case "return":
  26. front.resolve({
  27. value: value,
  28. done: !0
  29. });
  30. break;
  31. case "throw":
  32. front.reject(value);
  33. break;
  34. default:
  35. front.resolve({
  36. value: value,
  37. done: !1
  38. });
  39. }
  40. (front = front.next) ? resume(front.key, front.arg) : back = null;
  41. }
  42. this._invoke = function (key, arg) {
  43. return new Promise(function (resolve, reject) {
  44. var request = {
  45. key: key,
  46. arg: arg,
  47. resolve: resolve,
  48. reject: reject,
  49. next: null
  50. };
  51. back ? back = back.next = request : (front = back = request, resume(key, arg));
  52. });
  53. }, "function" != typeof gen["return"] && (this["return"] = void 0);
  54. }
  55. AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function () {
  56. return this;
  57. }, AsyncGenerator.prototype.next = function (arg) {
  58. return this._invoke("next", arg);
  59. }, AsyncGenerator.prototype["throw"] = function (arg) {
  60. return this._invoke("throw", arg);
  61. }, AsyncGenerator.prototype["return"] = function (arg) {
  62. return this._invoke("return", arg);
  63. };
  64. module.exports = AsyncGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;