1

I’m still confused at some of the advantages of ES6 Generators. How does,

app.use(function *(next){
  var start = new Date;
  yield next;
  var ms = new Date - start;
  this.set('X-Response-Time', ms + 'ms');
});

compare to something like,

app.use(function (next, ctx) {
  var start = new Date;
  next(ctx);
  var ms = new Date - start;
  ctx.set('X-Response-Time', ms + 'ms');
});

What makes generators so special for something like Koa? This is what Koa.js has to say about generators,

Contrasting Connect’s implementation which simply passes control through series of functions until one returns, Koa yields “downstream”, then control flows back “upstream”.

Isn’t that what my above pseudo code does?

Alex
  • 171
  • 2
  • 10
Evan Carroll
  • 78,363
  • 46
  • 261
  • 468

1 Answers1

3

next would be a regular function. since all middleware is considered asynchronous, next(ctx) would not wait until all the downstream middleware have completed processing. instead, what you effectively have is Express, which does not have the concept of "upstream".

you effectively have is:

app.use(function (downstream) {
  var start = Date.now();
  setImmediate(downstream);
  var ms = Date.now() - start;
  this.set('X-Response-Time', ms + 'ms');
})

which won't work since you're setting the response time on the same tick, not when all the downstream middleware is actually finished executing.

Jonathan Ong
  • 19,927
  • 17
  • 79
  • 118
  • Well, why does all middle ware have to be asynchronous? It's not asynchronous in Koa, right? Aren't all calls to `yield` synchronous? – Evan Carroll Jan 22 '14 at 22:09
  • 2
    it looks synchronous, but generators can be asynchronous or synchronous. `yield` means execution could have stopped, but you don't know if it's actually asynchronous from inside the generator. – Jonathan Ong Jan 23 '14 at 05:45
  • I have no idea what you're talking about still. I'm not sure if it's me or you. – Evan Carroll Jan 23 '14 at 08:09
  • Perhaps you could boil it down to a simple example of the generator paradigm and non-generator paradigm with why the same effect can't be had. – Evan Carroll Jan 23 '14 at 08:11