Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/wapython
Path: blob/main/core/kernel/src/wasm/reuseInFlight.js
1067 views
1
/* This is from the ISC licensed async-await-utils project, from here:
2
https://github.com/masotime/async-await-utils/blob/master/src/hof/reuseInFlight.js
3
Including that quite heavy (due to babel dep) project just for this one function
4
is a bit much, so I copy/pasted it here.
5
*/
6
7
const DEFAULT_CONFIG = {
8
createKey(args) {
9
return JSON.stringify(args);
10
},
11
ignoreSingleUndefined: false,
12
};
13
14
// for a given Promise-generating function, track each execution by the stringified
15
// arguments. if the function is called again with the same arguments, then instead
16
// of generating a new promise, an existing in-flight promise is used instead. This
17
// prevents unnecessary repetition of async function calls while the same function
18
// is still in flight.
19
export default function reuseInFlight(asyncFn, config) {
20
config = {
21
...DEFAULT_CONFIG,
22
...(config || {}),
23
};
24
25
const inflight = {};
26
27
return function debounced(...args) {
28
if (
29
config.ignoreSingleUndefined &&
30
args.length === 1 &&
31
args[0] === undefined
32
) {
33
console.warn("Ignoring single undefined arg (reuseInFlight)");
34
args = [];
35
}
36
37
const key = config.createKey(args);
38
if (!inflight.hasOwnProperty(key)) {
39
// WE DO NOT AWAIT, we are storing the promise itself
40
inflight[key] = asyncFn.apply(this, args).then(
41
(results) => {
42
// self invalidate
43
delete inflight[key];
44
return results;
45
},
46
(err) => {
47
// still self-invalidate, then rethrow
48
delete inflight[key];
49
throw err;
50
}
51
);
52
}
53
54
return inflight[key];
55
};
56
}
57
58