洋葱圈模型js实现

洋葱圈模型

什么是洋葱圈模型?
洋葱圈模型是一种函数执行机制,函数的执行想洋葱一样,从外圈到内圈再到外圈,使用过nodejs中的koa的都知道,在Koa框架中,洋葱圈模型的概念是指将中间件按照一定的顺序组织成一条链,并且在请求处理过程中,请求会依次经过这条链上的每个中间件。这些中间件可以在请求的处理过程中执行一些逻辑操作,例如验证请求、处理数据、修改响应等。洋葱圈模型的执行顺序是从外层中间件进入,然后依次经过内层中间件,最后再从外层中间件返回。
洋葱圈模型有什么用?
洋葱圈模型是一种面相切面编程思想,将横切关注点从主要业务逻辑中分离出来,以提高代码的可维护性和可重用性。这些横切关注点可以被多个请求共享,并与主要业务逻辑解耦,从而使代码更加模块化和可维护。
在这里插入图片描述

js代码实现

class Task_onion_ring {
    #tasks = []
    #current_task_index = 0
    #is_running = false
    addTask(task) {
        typeof task === "function" && this.#tasks.push(task)
    }
    async run() {
        if (this.#is_running) { // 避免多次调用
            return
        }
        this.#execute()
    }
    async #execute() {
        try {
            if (this.#current_task_index >= this.#tasks.length) {
                this.#is_running = false
                this.#current_task_index === 0
                this.#tasks.length = 0
                return
            }
            const current_task = this.#tasks[this.#current_task_index]
            this.#is_running = true
            const old_task_index = this.#current_task_index
            await current_task(this.#next.bind(this))
            const current_task_index = this.#current_task_index
            if (current_task_index === old_task_index) {
                this.#current_task_index ++
                this.#execute()
            }
        } catch (error) {
        	//错误处理
            console.log(error)
        }
    }
    #next() {
        this.#current_task_index++
        this.#execute()
    }
}
const t = new Task_onion_ring()
t.addTask(async (next) => {
    console.log(1, 'start')
    await next()
    console.log(1, 'end')
})
t.addTask(async (next) => {
    console.log(2, 'start')
    await next()
    console.log(2, 'end')
})
t.addTask(() => {
    console.log(3)
})
t.addTask(() => {
    console.log(4)
})
t.run()
t.run()
t.run()

结果展示

在这里插入图片描述

总结

  1. 介绍了什么是洋葱圈模型
  2. js实现
  3. 结果展示
  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大鲤余

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值