定义中间件对象
class Middleware { constructor({ core, params }) { // 传入的封装axios this.core = core; // 传入的axios参数 this.params = params; // 寄存链式调用的中间件函数 this.cache = []; } use(fn) { if (typeof fn !== "function") { throw "middleware must be a function"; } this.cache.push(fn); return this; } next(data) { if (this.middlewares && this.middlewares.length > 0) { var ware = this.middlewares.shift(); ware.call(this, this.next.bind(this), data); } return data; } async go() { // 申请获取数据,以备后序程序应用 let result = await this.core(this.params); //复制函数,待执行 this.middlewares = this.cache.map(function(fn) { return fn; }); // 向后传递参数,两头插件模型解决流程数据 this.next(result); }}
应用
// 导入参数var onion = new Middleware({core: request, params});onion.use(function (next, data) { console.log(1); console.log(data); // 向后传递数据 next(data); console.log("1完结");});onion.use(function (next, data) { console.log(2); console.log(data); // 向后传递数据 next(data); console.log("2完结");});onion.use(function (next, data) { console.log(3); console.log(data); console.log("3完结");});// 上一步没有调用next,前面的函数都不执行onion.use(function (next, data) { console.log(4); next(data); console.log("4完结");});onion.go();// 1// {a: 1, b: 2}// 2// {a: 1, b: 2, c: 3}// 3// {a: 1, b: 2, c: 3, d: 4}// 3完结// 2完结// 1完结// {a: 1, b: 2, c: 3, d: 4}
配合API接口数据返回后的操作函数
function handleStatus(next, res) { console.log(res); next(res);}function handleAuth(next, res) { console.log(res); next(res);}function handlePosition(next, res) { console.log(res); next(res);}function handleForbiddenList(next, res) { console.log(res); next(res);}function handleLoad(next, res) { console.log(res); next(res);}
通过中间件以此注册
// 导入参数var onion = new Middleware({core: request, params});onion.use(handleStatus);onion.use(handleAuth);onion.use(handlePosition);onion.use(handleForbiddenList);onion.use(handleLoad);onion.go();// 函数外面能够用异步函数,获取到这个流程解决完的值// let res = await onion.go();