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

【Q625】简述 koa 的中间件原理,手写 koa-compose 代码 #643

Open
shfshanyue opened this issue Jul 8, 2021 · 4 comments
Open

Comments

@shfshanyue
Copy link
Owner

No description provided.

@shfshanyue
Copy link
Owner Author

function compose (middlewares) {
  return ctx => {
    const dispatch = (i) => {
      const middleware = middlewares[i]
      if (i === middlewares.length) {
        return
      }
      return middleware(ctx, () => dispatch(i+1))
    }
    return dispatch(0)
  }
}

@haotie1990
Copy link

const middlewares = [];

middlewares.push(async function(ctx, next) {
  console.log('1');
  await next();
  console.log('6');
});

middlewares.push(async function(ctx, next) {
  console.log('2');
  await next();
  console.log('5');
});

middlewares.push(async function(ctx, next) {
  console.log('3');
  await next();
  console.log('4');
});

async function run() {
  const middleware = middlewares.shift();
  await (middleware && middleware({}, run));
}

run(); // expect output: 1 2 3 4 5 6

@shfshanyue
Copy link
Owner Author

@haotie1990 你这种实现,简洁多了!

@Asarua
Copy link

Asarua commented Jul 26, 2021

这个好棒

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants