-
Notifications
You must be signed in to change notification settings - Fork 0
/
asyncrify.js
96 lines (87 loc) · 2.25 KB
/
asyncrify.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
class Asyncrify {
constructor(options) {
// Cannot create on server: TODO child processes
if (typeof window === "undefined") {
if (!options.quiet) {
console.info("Asyncrify is a no-op server-side.");
}
return;
}
// Promise resolves to call when transmissions are received
this.resolves = {
exec: null,
close: null
};
// Get paths
this.localPath = window.location.href;
try { throw new Error(); }
catch(e) {
this.executingPath = e.stack.split("\n")
.map(s => s.match(/(https?:\/\/(.+?))\/asyncrify.js/))
.filter(Boolean)[0][1];
}
this.worker = new SharedWorker(this.executingPath + "/asyncrify.worker.js");
this.worker.port.start();
// Events
this.worker.port.addEventListener("message", e => {
// Take action
if (e.data.action) {
switch (e.data.action) {
case "console":
// Handle console proxy forwards
console[e.data.property].apply(console, e.data.args);
break;
case "exec":
// Resolve exec promise
if (typeof this.resolves.exec === "function") {
this.resolves.exec(e.data.result);
this.resolves.exec = null;
}
break;
case "close":
// Resolve stopWhenDone promise
if (typeof this.resolves.close === "function") {
this.resolves.close(e.data);
this.resolves.close = null;
}
break;
}
}
});
};
require(file) {
this.worker.port.postMessage({ action: "require", file: `${ this.localPath }/${ file }` });
};
exec(fn) {
return new Promise(resolve => {
this.resolves.exec = resolve;
this.worker.port.postMessage({ action: "exec", fn: fn.toString() });
});
};
stopWhenDone(delay) {
return new Promise(resolve => {
if (delay) {
setTimeout(() => {
this.resolves.close = resolve;
this.worker.port.postMessage({ action: "close" });
}, delay)
}
else {
this.resolves.close = resolve;
this.worker.port.postMessage({ action: "close" });
}
})
};
kill(delay) {
if (delay) {
setTimeout(() => {
this.worker.port.close();
}, delay);
}
else {
// Don't push to the bottom of the call stack with setTimeout, even with a zero-y value
this.worker.port.close();
}
};
};
if (typeof module !== "undefined" && module.exports) module.exports = Asyncrify;