-
Notifications
You must be signed in to change notification settings - Fork 0
/
concurrent.ts
73 lines (67 loc) · 1.91 KB
/
concurrent.ts
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
interface IWebWorkerMessageEvent<T> extends MessageEvent {
data: {
data: T,
rejected: boolean
}
}
export function concurrent<T> (target:Object,
propertyKey:string,
descriptor:TypedPropertyDescriptor<(...args:any[]) => Promise<T>>) {
// remember original function for later invokation as a normalized string (no linebreaks)
const _originalFunctionAsString = descriptor.value.toString().replace(/(\r\n|\n|\r)/gm, "");
// wrap original function by web worker
descriptor.value = function (...args:any[]) {
const promise = new Promise(
(resolve, reject) => {
// create object url from function
const objectUrl = URL.createObjectURL(
new Blob([`
self.addEventListener(
'message',
function (evt) {
var eventData = JSON.parse(evt.data),
scope = eventData.scope,
params = eventData.params,
fnGenerator = new Function("return ${_originalFunctionAsString}"),
fn = fnGenerator(),
resultingPromise = fn.apply(scope, params);
resultingPromise.then (
function (result) {
self.postMessage({
data: result,
rejected: false
});
},
function (error) {
self.postMessage({
data: error,
rejected: true
});
}
);
},
false
);
`], {type: 'application/javascript'})
);
// create web worker and release resources
const worker = new Worker(objectUrl);
URL.revokeObjectURL(objectUrl);
// add listeners to webworker
worker.onmessage = function (evt:IWebWorkerMessageEvent<T>) {
(evt.data.rejected ? reject : resolve)(evt.data.data);
};
worker.onerror = reject;
// start webworker
worker.postMessage(
JSON.stringify({
scope: this,
params: args
})
);
}
);
return promise;
};
return descriptor;
}