模拟koa洋葱模型实现

koa洋葱模型即是注册的中间件采取先进后出的运行策略。
在这里插入图片描述

问题

app.use(async next => {
    console.log(1);
    await next();
    console.log(2);
});
app.use(async next => {
    console.log(3);
    await next();
    console.log(4);
});

// 异步函数
function fn() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("hello");
        }, 3000);
    });
}
app.use(async next => {
    console.log(5);
    let res = await fn(); // 调用异步函数
    console.log(res)
    await next();
    console.log(6);
});

app.compose();

实现use与compose方法,预期输出如下结果

1
3
5
hello
6
4
2

方法实现

var app = {
    middlewares: []
};

// 创建 use 方法
app.use = function(fn) {
    app.middlewares.push(fn);
};

app.compose = function() {
    // 递归函数
    function dispatch(index) {
        // 如果所有中间件都执行完跳出
        if (index === app.middlewares.length) return Promise.resolve();

        // 取出第 index 个中间件并执行
        const middleware = app.middlewares[index];
        // 核心在这一行
        return Promise.resolve(middleware(() => dispatch(index + 1)));
    }

    // 取出第一个中间件函数执行
    dispatch(0);
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值