我在谷歌和书籍上研究了这个主题几个小时,但我只能找到非常具体的实现。我正在努力在 Node JS 中仅使用普通的 JavaScript 编写一个简单的中间件类(没有像 async、co 等附加模块)。我的目标是了解它是如何工作的而不是获得最优化的代码。
我想要像拥有一个字符串并通过使用中间件向其中添加新字符串一样简单的东西。
班上
"use strict";
class Middleware {
constructor() {
this.middlewares = [];
}
use(fn) {
this.middlewares.push(fn);
}
executeMiddleware(middlewares, msg, next) {
// This is where I'm struggling
}
run(message) {
this.executeMiddleware(this.middlewares, message, function(msg, next) {
console.log('the initial message : '+ message);
});
}
}
module.exports = Middleware;
Run Code Online (Sandbox Code Playgroud)
可能的用法
const Middleware = require('./Middleware');
const middleware = new Middleware();
middleware.use(function(msg, next) {
msg += ' World';
next();
});
middleware.use(function(msg, next) {
msg += ' …Run Code Online (Sandbox Code Playgroud)