forked from nolanlawson/promise-worker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
78 lines (65 loc) · 1.88 KB
/
index.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
'use strict';
/* istanbul ignore next */
var MyPromise = typeof Promise !== 'undefined' ? Promise : require('lie');
var messageIds = 0;
function parseJsonSafely(str) {
try {
return JSON.parse(str);
} catch (e) {
return false;
}
}
function onMessage(self, e) {
var message = parseJsonSafely(e.data);
if (!message) {
// Ignore - this message is not for us.
return;
}
var messageId = message[0];
var error = message[1];
var result = message[2];
var callback = self._callbacks[messageId];
if (!callback) {
// Ignore - user might have created multiple PromiseWorkers.
// This message is not for us.
return;
}
delete self._callbacks[messageId];
callback(error, result);
}
function PromiseWorker(worker) {
var self = this;
self._worker = worker;
self._callbacks = {};
worker.addEventListener('message', function (e) {
onMessage(self, e);
});
}
PromiseWorker.prototype.postMessage = function (userMessage) {
var self = this;
var messageId = messageIds++;
var messageToSend = [messageId, userMessage];
return new MyPromise(function (resolve, reject) {
self._callbacks[messageId] = function (error, result) {
if (error) {
return reject(new Error(error.message));
}
resolve(result);
};
var jsonMessage = JSON.stringify(messageToSend);
/* istanbul ignore if */
if (typeof self._worker.controller !== 'undefined') {
// service worker, use MessageChannels because e.source is broken in Chrome < 51:
// https://bugs.chromium.org/p/chromium/issues/detail?id=543198
var channel = new MessageChannel();
channel.port1.onmessage = function (e) {
onMessage(self, e);
};
self._worker.controller.postMessage(jsonMessage, [channel.port2]);
} else {
// web worker
self._worker.postMessage(jsonMessage);
}
});
};
module.exports = PromiseWorker;