asyncify-helpers.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.awaitEachYieldedPromise = exports.maybeAsync = exports.maybeAsyncFn = void 0;
  4. function* awaitYield(value) {
  5. return (yield value);
  6. }
  7. function awaitYieldOf(generator) {
  8. return awaitYield(awaitEachYieldedPromise(generator));
  9. }
  10. const AwaitYield = awaitYield;
  11. AwaitYield.of = awaitYieldOf;
  12. /**
  13. * Create a function that may or may not be async, using a generator
  14. *
  15. * Within the generator, call `yield* awaited(maybePromise)` to await a value
  16. * that may or may not be a promise.
  17. *
  18. * If the inner function never yields a promise, it will return synchronously.
  19. */
  20. function maybeAsyncFn(that, fn) {
  21. return (...args) => {
  22. const generator = fn.call(that, AwaitYield, ...args);
  23. return awaitEachYieldedPromise(generator);
  24. };
  25. }
  26. exports.maybeAsyncFn = maybeAsyncFn;
  27. class Example {
  28. constructor() {
  29. this.maybeAsyncMethod = maybeAsyncFn(this, function* (awaited, a) {
  30. yield* awaited(new Promise((resolve) => setTimeout(resolve, a)));
  31. return 5;
  32. });
  33. }
  34. }
  35. function maybeAsync(that, startGenerator) {
  36. const generator = startGenerator.call(that, AwaitYield);
  37. return awaitEachYieldedPromise(generator);
  38. }
  39. exports.maybeAsync = maybeAsync;
  40. function awaitEachYieldedPromise(gen) {
  41. function handleNextStep(step) {
  42. if (step.done) {
  43. return step.value;
  44. }
  45. if (step.value instanceof Promise) {
  46. return step.value.then((value) => handleNextStep(gen.next(value)), (error) => handleNextStep(gen.throw(error)));
  47. }
  48. return handleNextStep(gen.next(step.value));
  49. }
  50. return handleNextStep(gen.next());
  51. }
  52. exports.awaitEachYieldedPromise = awaitEachYieldedPromise;
  53. //# sourceMappingURL=asyncify-helpers.js.map