-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsthread.js
80 lines (71 loc) · 2.62 KB
/
jsthread.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
(function(global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.jsThread = global.jsThread || {})));
}(this, (function(exports) {
"use strict";
function createThread(init, imports, param) {
var url = window.location.href;
url = url.substring(0, url.lastIndexOf('/') + 1);
var global = [];
if (imports != undefined) {
for (var item of imports) {
global.push('importScripts(\'' + url + item + '\');');
// global.push('importScripts(\'' + self.location.origin + '/' + item + '\');');
}
}
var blob = new Blob(['\'use strict\';' + global.join('') + '(' + function(f) {
self.onmessage = function(e) {
var callable = f(e.data);
Promise.resolve(callable).then(function(f) {
if (typeof(f) == 'function') {
self.onmessage = function(e) {
var result = f(e.data);
// self.postMessage(result);
Promise.resolve(result).then(function(v) {
self.postMessage(v);
});
};
}
});
};
} + ')(' + init + ');'], {
type: "text/javascript"
});
var worker = new Worker(window.URL.createObjectURL(blob));
worker.postMessage(param);
return worker;
}
function createService(func) {
var channel = new MessageChannel();
channel.port1.onmessage = function(e) {
var result = func(e.data);
Promise.resolve(result).then(function(v) {
channel.port1.postMessage(v);
});
};
return channel.port2;
}
function callThread(worker, param) {
var promise = new Promise(function(resolve, reject) {
worker.onmessage = function(e) {
resolve(e.data);
};
worker.onerror = function(e) {
reject(e.message);
};
// setTimeout(function() {
// reject();
// }, 10000);
});
worker.postMessage(param);
return promise;
}
function endThread(worker) {
worker.terminate();
}
exports.createThread = createThread;
exports.createService = createService;
exports.callThread = callThread;
exports.endThread = endThread;
})));