KoaJS教程

Koa.js 生成器

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() 启动生成器并运行直到达到产量。然后它返回带有 value 和 done 的对象,其中 value 具有表达式 value。这个表达式可以是任何东西。此时,它暂停执行。当我们再次调用这个函数(next)时,生成器从最后一个屈服点恢复执行,暂停时函数状态相同,直到下一个屈服点。这样做直到代码中不再有屈服点。

Koa 中的生成器

那么为什么我们要在本教程中讨论生成器。您可能还记得在 hello world 程序中,我们使用 function* () 表示法将回调传递给 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 使用生成器的本质。它允许我们使用此属性创建紧凑的中间件,并为上游和下游功能编写代码,从而避免回调。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4