-
Notifications
You must be signed in to change notification settings - Fork 40
/
register.js
78 lines (69 loc) · 2.25 KB
/
register.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'
function isPromise (obj) {
// via https://unpkg.com/is-promise@2.1.0/index.js
return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'
}
function registerPromiseWorker (callback) {
function postOutgoingMessage (e, messageId, error, result) {
function postMessage (msg) {
/* istanbul ignore if */
if (typeof self.postMessage !== 'function') { // service worker
e.ports[0].postMessage(msg)
} else { // web worker
self.postMessage(msg)
}
}
if (error) {
/* istanbul ignore else */
if (typeof console !== 'undefined' && 'error' in console) {
// This is to make errors easier to debug. I think it's important
// enough to just leave here without giving the user an option
// to silence it.
console.error('Worker caught an error:', error)
}
postMessage([messageId, {
message: error.message
}])
} else {
postMessage([messageId, null, result])
}
}
function tryCatchFunc (callback, message) {
try {
return { res: callback(message) }
} catch (e) {
return { err: e }
}
}
function handleIncomingMessage (e, callback, messageId, message) {
var result = tryCatchFunc(callback, message)
if (result.err) {
postOutgoingMessage(e, messageId, result.err)
} else if (!isPromise(result.res)) {
postOutgoingMessage(e, messageId, null, result.res)
} else {
result.res.then(function (finalResult) {
postOutgoingMessage(e, messageId, null, finalResult)
}, function (finalError) {
postOutgoingMessage(e, messageId, finalError)
})
}
}
function onIncomingMessage (e) {
var payload = e.data
if (!Array.isArray(payload) || payload.length !== 2) {
// message doens't match communication format; ignore
return
}
var messageId = payload[0]
var message = payload[1]
if (typeof callback !== 'function') {
postOutgoingMessage(e, messageId, new Error(
'Please pass a function into register().'))
} else {
handleIncomingMessage(e, callback, messageId, message)
}
}
self.addEventListener('message', onIncomingMessage)
}
module.exports = registerPromiseWorker