Skip to main content
Module

x/async_call_rpc/docs/index.html

A lightweight JSON RPC client & server
Latest
File
<html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Playground</title> </head> <body> <a href="./async-call-rpc.html">See document</a> <hr /> The <code>AsyncCall, AsyncGeneratorCall, JSONSerialization, NoSerialization</code> is available in globalThis are available as the global variable <hr /> Call <code>define(fns)</code> to define a new demo JSON RPC server. Call <code>await sleep(ms)</code> to slow down the server. <script type="module"> import * as lib from 'https://cdn.jsdelivr.net/npm/async-call-rpc@latest/out/full.mjs' const { AsyncCall } = lib class PlayGroundChannel { static server = document.createElement('a') static client = document.createElement('a') // actor: 'server' | 'client' constructor(actor) { this.actor = actor PlayGroundChannel[actor].addEventListener('targetEventChannel', (e) => { const detail = e.detail for (const f of this.listener) { try { f(detail) } catch {} } }) } listener = [] on(_, cb) { this.listener.push(cb) } emit(_, data) { PlayGroundChannel[this.actor === 'client' ? 'server' : 'client'].dispatchEvent( new CustomEvent('targetEventChannel', { detail: data }), ) } } const server = new PlayGroundChannel('server') const client = new PlayGroundChannel('client') Object.assign(globalThis, lib) Object.assign(globalThis, { server, client, define, sleep }) let count = 0 function define(def, key = `server${count++}`) { // define server AsyncCall(def, { channel: server, key }) // define client globalThis[key] = AsyncCall({}, { channel: client, key }) console.log('Server is available as global variable', key, globalThis[key]) } function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)) } Object.assign(globalThis, AsyncCall) console.log('Try to run: await server0.add(42, 0)') define({ async add(a, b) { await sleep(1000) return a + b }, }) </script> </body></html>