UNPKG

1.66 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
11const gensync = require("gensync");
12
13const id = x => x;
14
15const runGenerator = gensync(function* (item) {
16 return yield* item;
17});
18const isAsync = gensync({
19 sync: () => false,
20 errback: cb => cb(null, true)
21});
22exports.isAsync = isAsync;
23
24function maybeAsync(fn, message) {
25 return gensync({
26 sync(...args) {
27 const result = fn.apply(this, args);
28 if (isThenable(result)) throw new Error(message);
29 return result;
30 },
31
32 async(...args) {
33 return Promise.resolve(fn.apply(this, args));
34 }
35
36 });
37}
38
39const withKind = gensync({
40 sync: cb => cb("sync"),
41 async: cb => cb("async")
42});
43
44function forwardAsync(action, cb) {
45 const g = gensync(action);
46 return withKind(kind => {
47 const adapted = g[kind];
48 return cb(adapted);
49 });
50}
51
52const onFirstPause = gensync({
53 name: "onFirstPause",
54 arity: 2,
55 sync: function (item) {
56 return runGenerator.sync(item);
57 },
58 errback: function (item, firstPause, cb) {
59 let completed = false;
60 runGenerator.errback(item, (err, value) => {
61 completed = true;
62 cb(err, value);
63 });
64
65 if (!completed) {
66 firstPause();
67 }
68 }
69});
70exports.onFirstPause = onFirstPause;
71const waitFor = gensync({
72 sync: id,
73 async: id
74});
75exports.waitFor = waitFor;
76
77function isThenable(val) {
78 return !!val && (typeof val === "object" || typeof val === "function") && !!val.then && typeof val.then === "function";
79}
\No newline at end of file