Sunday, June 21, 2015

JavaScript Backend: WebWorkers

Generation of async callbacks at transpilation time, from simple blocking logic, into callback-hell.

Async Transform

Using WebWorkers directly requires you define functions for postMessage and onmessage, split your JavaScript into two files, and load libraries in the worker with importScripts. Only low-level-chumps think dealing with these API's directly is a good idea. All these API details are easily abstracted away with syntax inspired from Golang. One of the best things about Golang is the message passing syntax: it makes code more readable, and it prevents a library-war by having this syntax builtin.

result1 = <- mychannel
print result1
result2 = <- mychannel
print result2

The code above gets the result of mychannel that computes something in a WebWorker. This requires waiting for the result, so if written directly by hand in JavaScript, you would need to write a mess of async callbacks. Rusthon automatically translates above into async code, and deals with routing messages to each channel.

__workerpool__.recv( mychannel, function (result1) {
 console.log(result1);
 __workerpool__.recv( mychannel, function (result2) {
  console.log(result2);
 });
});

source code

Channel Select Syntax

Select syntax inspired by Golang, works pretty much the same as Golangs select statement.


for i in range(n):
 print 'trying to select on workers'
 select:
  case res = <- worker1:
   show('case-worker1:' + res)
  case res = <- worker2:
   show('case-worker2:' + res)

example source code

1 comment: