Skip to content

Instantly share code, notes, and snippets.

@teal-front
Last active November 8, 2021 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teal-front/b43572667dc065c3be103ed39da8597b to your computer and use it in GitHub Desktop.
Save teal-front/b43572667dc065c3be103ed39da8597b to your computer and use it in GitHub Desktop.
threads
/**
* rpc mini impl
* @author 神说要有光
*/
let id = 0
function getId() {
return id++
}
const callMap = new Map()
function rpc(method, params) {
const curId = getId()
postMessage({
messageId: curId,
method,
params
})
return new Promise((resolve, reject) => {
callMap.set(curId, {
resolve,
reject
})
})
}
addEventListener('message', (evt) => {
const { messageId, res, method, params } = evt.data
if (res) {
const { resolve, reject } = callMap.get(messageId)
if (res.error) {
reject(res.error)
} else {
resolve(res.data)
}
} else {
try {
const res = this[method](...params)
postMessage({
messageId,
data: res
})
} catch(e) {
postMessage({
messageId,
error: e
})
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment