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/koa-vs-express.md at master koajs/koa #37

Open
TopGrd opened this issue Aug 30, 2019 · 2 comments
Open

koa/koa-vs-express.md at master koajs/koa #37

TopGrd opened this issue Aug 30, 2019 · 2 comments

Comments

@TopGrd
Copy link
Owner

TopGrd commented Aug 30, 2019

koa/koa-vs-express.md at master · koajs/koa

Philosophically, Koa aims to "fix and replace node", whereas Express "augments node".Koa uses promises and async functions to rid apps of callback hell and…



August 30, 2019 at 04:32PM

via Instapaper https://ift.tt/1mz3cgb

@TopGrd
Copy link
Owner Author

TopGrd commented Aug 30, 2019

function compose(middlewares) {
  return function middleware(ctx, next) {
    let index = -1;
    function dispatch(n) {
      if (n <= index) return Promise.reject(new Error('multitime call midware'));
      index = n;
      let fn = middlewares[n];
      if (n === middlewares.length) fn = next;
      if (!fn) return Promise.resolve();

      try {
        return Promise.resolve(fn(ctx, () => dispatch(n + 1)));
      } catch (error) {
        return Promise.reject(error);
      }
    }

    return dispatch(0);
  };
}

@TopGrd
Copy link
Owner Author

TopGrd commented Aug 30, 2019

简单模拟

function express() {
  const app = { middlewares: [] };
  app.use = function use(middleware) {
    app.middlewares.push(middleware);
  };

  const req = {};
  const res = {};
  let i = 0;
  function next() {
    if (i === app.middlewares.length) {
      return;
    }
    const fn = app.middlewares[i++];
    fn.call(app, req, res, next);
  }

  app.listen = function listen(port, callback) {
    callback(port);
    next();
  };

  return app;
}

const app = express();
app.use((req, res, next) => {
  console.log('ss1');
  req.body = { name: 'as' };
  next();
  console.log('ss2');
});

app.use((req, res, next) => {
  console.log(req);
  console.log('ss4');
  next();
  console.log('ss5');
});

app.listen(3000, (port) => {
  console.log('listen start', port);
});

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