-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
60 lines (50 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
60
'use strict';
if (!global.continuify) {
polyfillContinuify(global);
require('./lib/instrument')();
}
function polyfillContinuify(exports) {
let contextCounter = 0;
let continuationCounter = 0;
let linkCounter = 0;
const CONTINUATION = Symbol('Continuation')
const state = Object.create(null);
state.context = null;
class Context {
constructor(continuation) {
this.id = ++contextCounter;
this.continuation = continuation;
this.readyContext = null;
}
}
class ContinuationLinkData {
constructor(context) {
// The link context is the context active when the continuation is constructed.
this.id = ++linkCounter;
this.linkContext = context;
}
}
const continuify = (fn) => {
// Don't wrap non-functions or double-wrap continuations.
if (typeof fn !== 'function' || fn[CONTINUATION]) {
return fn;
}
const continuation = function(...args) {
const context = new Context(continuation);
const prev = state.context;
state.context = context;
try {
return fn.apply(this, args);
} finally {
state.context = prev;
}
};
continuation[CONTINUATION] = true;
continuation.id = ++continuationCounter;
continuation.original = fn;
continuation.linkData = new ContinuationLinkData(state.context);
return continuation;
};
exports.continuify = continuify;
exports.getCurrentContext = () => state.context;
}