Call Functions Across a Message Channel

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code
  • Pro

Write expose(port, handlers) and connect(port, options), to call functions across a message channel, such as between a page and a web worker or an iframe. A port has postMessage(data), which delivers a copy of data to the other end, later (plain data only: no functions or Error objects), and addEventListener("message", listener), whose listener gets an event with the data as event.data. expose answers calls arriving at its port by running handlers[method](...args). connect returns { call(method, ...args) }, which asks the other end to run that handler and returns a promise of its result. Handlers may return a value or a promise. If a handler throws or rejects, call rejects with an Error with the same message; if handlers has no function of that name of its own (inherited ones such as toString don't count), call rejects with an Error whose message is "Unknown method: " followed by the name. Several calls may be waiting at once, and replies can come back in any order. The same port may both expose and connect, the other end may do the same, and the channel may carry other messages, which both ignore. With options.timeout set, a call that has no reply after that many milliseconds rejects with an Error whose message is "Timed out", and a reply that comes later is ignored. options may be left out. The checks use waits of up to 80 milliseconds.

Your code must pass

  • Calls a function on the other side and gets its result
  • Waits for async handlers
  • Matches replies to the right calls
  • Rejects with the error from the other side
  • Rejects calls to unknown methods
  • Works both ways on one channel and ignores other messages
  • Times out when no reply comes