我正在开发一个函数管道,有点类似于使用 use() 的 Connect/Express 请求管道。
请求处理程序通过使用 .use() 函数添加的函数堆栈运行。异步,因为必须调用 an() 函数才能继续。
使用熟悉的 (req, res, next) 调用函数。这行得通,但它最后添加的第一个执行,我觉得令人困惑,我想让它首先添加第一个执行。这适用于最后一个并继续整个管道中的 r, s 引用。
(在这些示例中,我使用 r, s 而不是 req, res ..)
var s = {
chain: function(r, s, n){
// this runs last, was first added
s.end();
},
use: function (f){
this.chain = (function(nxt){
return function(r, s, n){
f(r, s, nxt.bind(this, r, s));
}
})(this.chain);
},
listen: function (){
this.use(function (r, s, n){
// this runs first, was last added
n();
})
var svr = require('http').createServer(this.chain);
svr.listen.apply(svr, [].slice.call(arguments)); // accept same args
}
}
s.use(function(r,s,n){...});
s.use(function(r,s,n){...});
s.listen(8080);
这是 FIFO 的尝试。但它不起作用。想法?
var chain = function(r, s, n){
console.log(1, arguments);
n();
};
function use(f){
var th = chain;
chain = (function(nxt){
return function(r, s){
th(r, s, nxt);
}
})(f);
}
use(function(r, s, n){
console.log(2, arguments)
n();
})
use(function(r, s, n){
console.log(3, arguments)
n();
})
chain(0,1);
想要一些不使用循环来运行函数的东西。