-
Notifications
You must be signed in to change notification settings - Fork 40
/
index.js
67 lines (55 loc) · 1.61 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
'use strict'
var messageIds = 0
function onMessage (self, e) {
var message = e.data
if (!Array.isArray(message) || message.length < 2) {
// 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 Promise(function (resolve, reject) {
self._callbacks[messageId] = function (error, result) {
if (error) {
return reject(new Error(error.message))
}
resolve(result)
}
/* 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(messageToSend, [channel.port2])
} else {
// web worker
self._worker.postMessage(messageToSend)
}
})
}
module.exports = PromiseWorker