Last active
November 8, 2021 15:53
-
-
Save teal-front/b43572667dc065c3be103ed39da8597b to your computer and use it in GitHub Desktop.
threads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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