UNPKG

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