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解析 #31

Open
L-small opened this issue May 6, 2020 · 0 comments
Open

koa解析 #31

L-small opened this issue May 6, 2020 · 0 comments

Comments

@L-small
Copy link
Owner

L-small commented May 6, 2020

洋葱模型原理

主要用了generator、co、Promise来实现的。主要为了解决复杂操作的频繁回调
image
当收到请求,co执行执行第一个的resolve()方法,触发其中的next(也就是yield)然后继续执行后面的promise

new Promise(function(resolve, reject) {
  // 我是中间件1
  yield new Promise(function(resolve, reject) {
    // 我是中间件2
    yield new Promise(function(resolve, reject) {
      // 我是中间件3
      yield new Promise(function(resolve, reject) {
        // 我是body
      });
      // 我是中间件3
    });
    // 我是中间件2
  });
  // 我是中间件1
});


compose(middlewares, ctx){
    function dispatch (index) {
        if (index === middlewares.length) return Promise.resolve()
        let middleware = middlewares[index]
        return Promise.resolve(middleware(ctx, () => dispatch(index + 1)))
    }
    return dispatch(0)
}

作者:rocYoung
链接:https://juejin.im/post/5ba48fc4e51d450e704277fa
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

context.js

这部分就是koa的应用上下文ctx,其实就一个简单的对象暴露,里面的重点在delegate,这个就是代理,这个就是为了开发者方便而设计的,比如我们要访问ctx.repsponse.status但是我们通过delegate,可以直接访问ctx.status访问到它

request.js、response.js

这两部分就是对原生的res、req的一些操作了,大量使用es6的get和set的一些语法,去取headers或者设置headers、还有设置body等等,这些就不详细介绍了,有兴趣的读者可以自行看源码

app.use

其实是在收集中间件

@L-small L-small changed the title 面试——koa解析 koa解析 May 8, 2020
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