CNode

koa写中间件的一个小问题,求助

Ggws321发布于12 年前最后回复12 年前5 回复9382 浏览0 收藏

在koa里面写中间件,格式是这样:

module.exports = function(opts){
    return function *(next){
        yield next;
    }
}

每次接收到请求都会走一遍return的生成器函数

但是我现在想在生成器函数外面,也就是在启动程序的时候执行其他生成器函数,请问怎么做? 就是下面这样,在程序加载的时候执行yield test();而不是在return function *(){}里面每次用户请求时执行

module.exports = function(opts){
    return function *(next){
        yield next;
    }
    function *test(){
        ....
    }
}
查看回复

回复 (5)

F
fundon#1·12 年前

或许这里需要引入co

co(function () {
 
  yield test();   

  // app
  // app.use(foo);

})();
G
gws321#2·12 年前
var co = require('co');
module.exports = function(opts){
    co(function () {
        yield test();   
    })();
    return function *(next){
        yield next;
    }
    function *test(){
        ....
    }
}

是这样吗?报错啊

/usr/local/bin/node -harmony app.js
/Users/gongwenshuo/Project/koa/node_modules/koa-test/index.js:111
        yield aaa();
              ^^^
SyntaxError: Unexpected identifier
    at exports.runInThisContext (vm.js:69:16)
    at Module._compile (module.js:432:25)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:349:32)
    at Function.Module._load (module.js:305:12)
    at Module.require (module.js:357:17)
    at require (module.js:373:17)
    at Object.<anonymous> (/Users/gongwenshuo/Project/koa/app.js:3:15)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)

Process finished with exit code 1
G
gws321#3·12 年前

搞定了谢谢!!!

var co = require('co');
module.exports = function(opts){
    co(function *() {
        yield test();   
    })();
    return function *(next){
        yield next;
    }
    function *test(){
        ....
    }
}
F
freew01f#4·12 年前

看来koa关注的人不少 我这几天也忙着写中间件~ 不知道大家koa是玩还是商业项目 我是正正经经搞商业项目

R
rekey#5·12 年前
function * test(){

}
module.exports = function * (next) {
  yield test();
};
参与回复
登录后即可参与回复。登录