【问题标题】:node.js - koa: generator don't go nextnode.js - koa:生成器不要下一个
【发布时间】:2016-02-04 00:22:58
【问题描述】:

我有一个简单的对象,我在其中传递一个参数,然后我想在我的集合中找到所有文档并标记它。这是我的自定义对象:

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 );

我是这样创建对象的:

var widget  = new Widget("text","Titiolo",0,0,"text.html","sections");

在我的控制台上我只看到“1”而不是 2 或“objects:”为什么?

【问题讨论】:

    标签: javascript node.js koa


    【解决方案1】:

    这与koa 无关。这就是生成器的工作方式。 .next() 评估代码直到下一个 yield 函数。因为您的生成器函数中有 1 个 yield,所以您需要调用 .next() 两次才能完成整个函数的评估,包括最后两个 console.log()s

    另外,你的 try/catch 块没有做任何事情。

    【讨论】:

      猜你喜欢
      • 2017-03-16
      • 1970-01-01
      • 2014-12-25
      • 1970-01-01
      • 2014-05-31
      • 2020-08-24
      • 2015-10-11
      • 2015-12-16
      • 2018-08-12
      相关资源
      最近更新 更多