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}
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();