Koa.js - Generators

JavaScript ES6最激动人心的新功能之一是一种新的功能,称为生成器.在生成器之前,整个脚本通常用于从上到下的顺序执行,没有简单的方法来停止代码执行并在以后使用相同的堆栈重新启动.生成器是可以退出并稍后重新输入的功能.它们的上下文(变量绑定)将在重新入口处保存.

生成器允许我们在两者之间停止代码执行.因此,让我们看看一个简单的生成器.

var generator_func = function* (){
   yield 1;
   yield 2;
};

var itr = generator_func();
console.log(itr.next());
console.log(itr.next());
console.log(itr.next());


运行上面的代码时,结果如下.

{ value: 1, done: false }
{ value: 2, done: false }
{ value: undefined, done: true }


让我们看看上面的代码.我们首先创建一个名为 generator_func()的生成器.我们创建了这个奇怪外观函数的实例,并将其分配给 itr .然后我们开始在这个itr变量上调用 next().

调用next()启动生成器并运行直到达到yield.然后它返回带有value和done的对象,其中值具有表达式值.这个表达可以是任何东西.此时,它暂停执行.再次当我们调用此函数(下一个)时,生成器从最后一个屈服点恢复执行,其中函数状态在暂停时是相同的,直到下一个屈服点.这样做直到代码中没有更多的屈服点.

Koa中的生成器

那么为什么我们在本教程中讨论生成器.您可能还记得hello world程序,我们使用函数*()表示法将回调传递给app.use(). Koa是一个对象,它包含一系列中间件生成器函数,所有这些函数都是在每次请求时以类似堆栈的方式组合和执行的. Koa还实现了下游,然后是控制流的上游.

看一下以下示例,以更好的方式理解这一点.

var koa = require('koa');
var app = koa();
 
app.use(function* (next) {
   //do something before yielding to next generator function 
   
   //in line which will be 1st event in downstream
   console.log("1");
   yield next;
 
   //do something when the execution returns upstream, 
   //this will be last event in upstream
   console.log("2");
});
app.use(function* (next) {
   // This shall be 2nd event downstream
   console.log("3");
   yield next;
 
   // This would be 2nd event upstream
   console.log("4");
});
app.use(function* () { 
   // Here it would be last function downstream
   console.log("5");
   
   // Set response body
   this.body = "Hello Generators";

   // First event of upstream (from the last to first)
   console.log("6");
});

app.listen(3000);


运行上面的代码并导航到 https://localhost:3000/时,我们在控制台上获得以下输出.

 
 1 
 3 
 5 
 6 
 4 
 2


这实际上是Koa使用生成器的方式.它允许我们使用此属性创建紧凑的中间件,并为上游和下游功能编写代码,从而使我们免于回调.