Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

koa洋葱模型核心函数(compose) #84

Open
dcharlie123 opened this issue Sep 18, 2022 · 0 comments
Open

koa洋葱模型核心函数(compose) #84

dcharlie123 opened this issue Sep 18, 2022 · 0 comments

Comments

@dcharlie123
Copy link
Owner

function compose(middleware) {
  // 判断是否是数组
  if (!Array.isArray(middleware)) {
    return;
  }
  // 判断每个中间件是否是函数
  for (const fn of middleware) {
    if (typeof fn !== "function") throw new Error("err");
  }
  return function (context, next) {
    let index = -1;
    function dispatch(i) {
      // 防止next在同个中间件多次调用
      if(i<=index) return Promise.reject(new Error('next() called multipe times'))
      index = i;
      let fn = middleware[index];
      if (index === middleware.length) {
        fn = next;
      }
      if (!fn) return Promise.resolve();
      try {
        return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
      } catch (err) {
        return Promise.reject(err);
      }
    }
    return dispatch(0);
  };
}
function a(window,next){
  console.log('1b')
  next()
  next()
  console.log('1a')
}
function b(window,next){
  console.log(2)
  next()
  console.log(3)
}
let fns=compose([a,b])
fns().then(()=>{console.log('over')})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant