-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
59 lines (53 loc) · 1.44 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
const JarvisEmitter = require("jarvis-emitter");
function meaco(genFunction, ...args) {
const promiseRet = new JarvisEmitter();
let rejected = false;
const caller = genFunction(...args);
function nextCall(lastWasError, ...args) {
if (lastWasError) {
promiseRet.callError(...args);
return;
}
let nextYield;
try {
nextYield = caller.next(...args);
} catch (e) {
promiseRet.callCatch(e);
return;
}
// was it rejected?
if (rejected) {
return;
}
const done = nextYield.done;
let promise = nextYield.value;
let fn = "then";
let catchFn = "";
const errorFn = "error";
if (!promise || done) {
promiseRet.callDone(promise);
return;
}
if (typeof promise === "object" && promise.promise && promise.fn) {
({ promise, fn } = promise);
} else if (promise.constructor.name === "JarvisEmitter" || (promise instanceof JarvisEmitter)) {
// this will not work in case promise is and instance of JarvisEmitter and code is minified
fn = "done";
catchFn = "catch";
}
if (promise[fn]) {
promise[fn](nextCall.bind(this, false), nextCall.bind(this, true));
if (promise[errorFn]) {
promise[errorFn](nextCall.bind(this, true));
}
if (catchFn && promise[catchFn]) {
promise[catchFn](promiseRet.callCatch.bind(this));
}
return;
}
promiseRet.callDone(promise);
}
nextCall(false);
return promiseRet;
}
module.exports = meaco;