Hurry
Maple
Lad

Fibrous on Harmony Generators? Impossible

Crossposted from bites.goodeggs.com

A good Friday afternoon chat about asynchronous programming models left me wondering if the fibrous API could be implemented on top of ES6 generators. Generators are baked in to Node 0.11, Chrome 19, and Firefox. A port would be a big boost to interoperability. Traceur can even transform generator based code into a giant state machine that runs on all of today's environments.

At first the port looked promising. Wikipedia claimed that general coroutines could be built on generators, and many folks have done just that. After a little noodling I'm pretty sure it can't be done. In a Harmony environment a function can only suspend execution at yield expressions and yield expressions can only appear in generator functions. A yield expression cannot be wrapped up behind a fibrous sync or wait.

Let's say we've got a fibrous function f that synchronously calls asychronous function g:

var g = function(callback) {
  setTimeout(function() {
    console.log('g done');
    callback();
  }, 1000);
};

var f = fibrous(function() {
  g.sync();
  console.log('f done');
};

When we call f we wait one second, log 'g done', then log 'f done'. We need to halt f before the console.log, but f has no yield expressions. It cannot be halted with any combination of ES6 generators. Tough break.