koa写中间件的一个小问题,求助 - CNode技术社区

koa写中间件的一个小问题,求助
发布于 12 年前 作者 gws321 9135 次浏览 最后一次编辑是 9 年前

在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 回复

或许这里需要引入co

co(function () {
 
 yield test(); 
 // app
 // app.use(foo);
})();
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

搞定了谢谢!!!

var co = require('co');
module.exports = function(opts){
 co(function *() {
 yield test(); 
 })();
 return function *(next){
 yield next;
 }
 function *test(){
 ....
 }
}
function * test(){
}
module.exports = function * (next) {
 yield test();
};

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

回到顶部

AltStyle によって変換されたページ (->オリジナル) /