async.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.forwardAsync = forwardAsync;
  6. exports.isAsync = void 0;
  7. exports.isThenable = isThenable;
  8. exports.maybeAsync = maybeAsync;
  9. exports.waitFor = exports.onFirstPause = void 0;
  10. function _gensync() {
  11. const data = require("gensync");
  12. _gensync = function () {
  13. return data;
  14. };
  15. return data;
  16. }
  17. const id = x => x;
  18. const runGenerator = _gensync()(function* (item) {
  19. return yield* item;
  20. });
  21. const isAsync = _gensync()({
  22. sync: () => false,
  23. errback: cb => cb(null, true)
  24. });
  25. exports.isAsync = isAsync;
  26. function maybeAsync(fn, message) {
  27. return _gensync()({
  28. sync(...args) {
  29. const result = fn.apply(this, args);
  30. if (isThenable(result)) throw new Error(message);
  31. return result;
  32. },
  33. async(...args) {
  34. return Promise.resolve(fn.apply(this, args));
  35. }
  36. });
  37. }
  38. const withKind = _gensync()({
  39. sync: cb => cb("sync"),
  40. async: cb => cb("async")
  41. });
  42. function forwardAsync(action, cb) {
  43. const g = _gensync()(action);
  44. return withKind(kind => {
  45. const adapted = g[kind];
  46. return cb(adapted);
  47. });
  48. }
  49. const onFirstPause = _gensync()({
  50. name: "onFirstPause",
  51. arity: 2,
  52. sync: function (item) {
  53. return runGenerator.sync(item);
  54. },
  55. errback: function (item, firstPause, cb) {
  56. let completed = false;
  57. runGenerator.errback(item, (err, value) => {
  58. completed = true;
  59. cb(err, value);
  60. });
  61. if (!completed) {
  62. firstPause();
  63. }
  64. }
  65. });
  66. exports.onFirstPause = onFirstPause;
  67. const waitFor = _gensync()({
  68. sync: id,
  69. async: id
  70. });
  71. exports.waitFor = waitFor;
  72. function isThenable(val) {
  73. return !!val && (typeof val === "object" || typeof val === "function") && !!val.then && typeof val.then === "function";
  74. }