class Midware {
midwares = []
use(fn) {
this.midwares.push(fn)
}
start(initialCtx) {
this.dispatch(0, initialCtx);
}
dispatch(index, ctx) {
let current = this.midwares[index];
if (index == this.midwares.length) {
return Promise.resolve('所有执行完了');
}
return current(ctx, () => this.dispatch(index + 1, ctx))
}
}
var ware = new Midware();
ware.use(async (ctx, next) => {
ctx.age = 20;
const result = await next()
result.push('执行完了1')
ctx.response = result;
})
ware.use(async (ctx, next) => {
ctx.name = 'kerry';
const result = await next()
result.push('执行完了2')
return result;
})
ware.use(async (ctx, next) => {
ctx.money = 100000000000;
const result = await next()
return [result];
})
let context = {}
ware.start(context)
console.log(context)
模拟一个超级简单的中间件
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 背景 在项目中经常会遇到一些通过URL链接来动态调用一些功能,或者是一个Safari中通过URL打开我们的App中...
- 使用ajax进行表单提交的时候,有多种方式可以选择,其中react提供的思路,将数据单独存放到state中进行操作...
- 有了redux相关组件,也不能达到完全准确定位bug的一个目的,这时候就需要日志来记录我们的action操作。有一...