Can node-fibers be implemented using ES6 generators?

1.1k views Asked by At
3

There are 3 answers

1
Jeff Ling On

Are you looking for something like https://github.com/visionmedia/co ?

From the README:

var co = require('co');

co(function *(){
  var a = yield get('http://google.com');
  var b = yield get('http://yahoo.com');
  var c = yield get('http://cloudup.com');
  console.log(a.status);
  console.log(b.status);
  console.log(c.status);
})()

co(function *(){
  var a = get('http://google.com');
  var b = get('http://yahoo.com');
  var c = get('http://cloudup.com');
  var res = yield [a, b, c];
  console.log(res);
})()

There is a new web framework called koa (http://koajs.com) that's based on this.

3
hurrymaplelad On

I tried to port a very small subset and failed. The crux was that node-fibers's Fiber.yield() halts execution all the way up the Fiber's call stack, while a generator's yield only halts the immediate function. While you may be able to implement a system that behaves similarly (like Task.js), it seems an API compatible implementation is impossible.

0
Lucio M. Tato On

I've coded a wrapper around Fibers called wait.for: https://github.com/luciotato/waitfor

Then I've coded the same functionality with generators: https://github.com/luciotato/waitfor-ES6

You can compare both to see how Generators can replace node-Fibers, but with different syntax.

One important difference, which makes impossible to have the same API, is that ES6's generators bodies are implemented with a special syntax: function* while node-fibers allows you use any js function.