1

Wikipedia suggests that coroutines can be implemented with generators. Does this mean node-fibers could be implemented using ES6 generators?

hurrymaplelad
  • 26,645
  • 10
  • 56
  • 76

3 Answers3

3

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.

Jeff Ling
  • 1,032
  • 9
  • 12
  • Good stuff. Thanks for the heads up. I was wondering if it's possible to build something that's syntax compatible with [fibrous](https://github.com/goodeggs/fibrous) on top of generators. I believe it's not. – hurrymaplelad Jan 03 '14 at 06:53
1

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.

Lucio M. Tato
  • 5,639
  • 2
  • 31
  • 30
0

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.

hurrymaplelad
  • 26,645
  • 10
  • 56
  • 76