node.js – koa:发电机不要下一步
我有一个简单的对象,我传递一个参数,然后我想find我的集合中的所有文件,并加盖它。 这是我的自定义对象:
var db = require('../lib/db'); function Widget(n,l,c,o,t,p) { this.name = n; this.label = l; this.class = c; this.order = o; this.template = t; this.params = p; if(this.params != null) { var a = getValue(this.params); a.next(); } } function *getValue(p){ var Object = require("./sections"); console.log("1"); try { var objects = yield Object.find({}).exec(); } catch(err){ throw err; } console.log("2"); console.log("obj:" + objects); } module.exports = Widget;
这是sections.js
var db = require('../lib/db'); var schema = new db.Schema( { title: String, parent: { type: db.Schema.ObjectId, ref: 'sections' }, child: [{ type: db.Schema.ObjectId, ref: 'sections' }], updated_on: Date, created_on: Date }); module.exports = db.model( 'sections', schema );
我以这种方式创build对象:
var widget = new Widget("text","Titiolo",0,0,"text.html","sections");
在我的控制台上我只看到“1”而不是2或“对象:”为什么?
这与koa
无关。 这只是发电机的工作原理。 .next()
计算代码直到下一个yield
函数。 因为在生成器函数中有1个yield
,所以需要调用.next()
两次来完成整个函数的计算,包括最后两个console.log()
另外,你的try / catch块不会做任何事情。