-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
dynamics_browser.js
112 lines (92 loc) · 2.56 KB
/
dynamics_browser.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Simple implementation of dynamic scoping, for use in browsers
var nextSlot = 0;
var currentValues = [];
var callAsyncMethodRunning = false;
Meteor.EnvironmentVariable = function () {
this.slot = nextSlot++;
};
var EVp = Meteor.EnvironmentVariable.prototype;
EVp.getCurrentValues = function () {
return currentValues;
};
/**
* @memberof Meteor.EnvironmentVariable
* @method get
* @returns {any} The current value of the variable, or its default value if
*/
EVp.get = function () {
return currentValues[this.slot];
};
EVp.getOrNullIfOutsideFiber = function () {
return this.get();
};
/**
* @memberof Meteor.EnvironmentVariable
* @method withValue
* @param {any} value The value to set for the duration of the function call
* @param {Function} func The function to call with the new value of the
* @returns {any} The return value of the function
*/
EVp.withValue = function (value, func) {
let ret
let isPromise
const saved = currentValues[this.slot];
try {
currentValues[this.slot] = value;
ret = func();
isPromise = Meteor._isPromise(ret);
if (isPromise) {
return ret.finally(() => {
currentValues[this.slot] = saved;
});
}
} finally {
if (!isPromise) {
currentValues[this.slot] = saved;
}
}
return ret;
};
EVp._set = function (context) {
currentValues[this.slot] = context;
};
EVp._setNewContextAndGetCurrent = function (value) {
var saved = currentValues[this.slot];
this._set(value);
return saved;
};
EVp._isCallAsyncMethodRunning = function () {
return callAsyncMethodRunning;
};
EVp._setCallAsyncMethodRunning = function (value) {
callAsyncMethodRunning = value;
};
Meteor.bindEnvironment = function (func, onException, _this) {
// needed in order to be able to create closures inside func and
// have the closed variables not change back to their original
// values
var boundValues = currentValues.slice();
if (!onException || typeof(onException) === 'string') {
var description = onException || "callback of async function";
onException = function (error) {
Meteor._debug(
"Exception in " + description + ":",
error
);
};
}
return function (/* arguments */) {
var savedValues = currentValues;
try {
currentValues = boundValues;
var ret = func.apply(_this, arguments);
} catch (e) {
// note: callback-hook currently relies on the fact that if onException
// throws in the browser, the wrapped call throws.
onException(e);
} finally {
currentValues = savedValues;
}
return ret;
};
};