A, according to Koa

  1. KoaIs made up ofExpressThe original cast, but compared toExpressLarge and complete,KoaIt’s small and fine.KoaNot having a lot of frameworks and plugins tied in makes it easier to extend, including the popular onesEggJS and ThinkJSAre based onKoaThe development of.
  2. KoaInstead of calling Express middleware in the form of callback, it uses our new VERSION of JS features,Koa1Middleware with our helpco and generatorFeatures,Koa2With the help of thePromise and async awaitFeatures, better flow control and catch our errors.
  3. KoaprovidesContextObject, actually, to our noderequest and responseObject encapsulation, we don’t need a lot of manual handling of ourrequest and responseObject.ContextIs throughout our entire request process, we can middleware needs to pass parameters to hang toContextOn the object. (Chestnut: We can hang user information on it, throughctx.state.userTo operate.)
  4. KoaMiddleware execution mechanism:Onion ring model. It is not executed sequentially, multiple middleware forms oneAfter the advancedThe current middleware controls the execution right of the next middleware, which is very effective for the realization of flow control and post-processing logic.

Ii. Comparison of Koa2 and Koa1

  1. Middleware management mode:Koa1With the help ofco and generatorManaging our middleware,Koa2With the help ofasync awaitAsync returnsPromiseObject) manages our middleware.
  2. contextObject to obtain:Koa1throughthisObject (this.req.this.res),Koa2throughctxParameters (ctx.req.ctx.res).
  3. Community maturity:Koa2The wheels are more mature and ecological thanKoa1Rich.

Three, for example, analyze the source code

1. The chestnuts

listen
3000
use
koa
console

2. Start with the Listen method

  1. First, clone the latest Koa source code on Github. Then the source code structure is as follows:

  1. You can see the whole source code is the core codelibFiles, we’re in chestnutsrequire('koa')It’s actually introducedlib/application.jsThe inside of theApplicationClass. Now let’s analyze ourslistenMethod implementation, let’s look at this firstApplicationWhat exactly is in the class:

  1. We can see thatApplicationWe have ours under the classlistenMethods: The methods are as follows:

This.callback() is the input to createServer, which is a function that listens to the request event and receives req and RES, which are our request object and response object. We can infer that this.callback() in listen actually returns a function that takes req and RES.

  1. Now let’s look at this onethis.callback()Callback (); callback ();

The compose method is important to control the execution of our middleware

This method takes two parameters: fn, the return result of our compose, and our CTX object. This method is responsible for the processing of our request and the uniform capture and processing of errors.

3. Implement our chestnuts: Take a look at the middleware implementation mechanism

Koa’s middleware implementation mechanism is known figuratively as the Onion Ring model. Let’s run the chestnut code and see what the output looks like.

4. Start by understanding the Use method

Push the middleware function we passed in to the this.middleware array

5. The core of the middleware execution mechanism is compose

Compose (this.middleware) : compose(callback) : compose(this.middleware)

  1. First, verify that our middleware parameters are correct, whether the array is an array, whether the array items are functions;
  2. The compose function actually returns a function, which, as mentioned above, is eventually passed to the handleRequest method and then the CTX argument: fnMiddleware(context).
  3. Returning to the function of our compose return, we receive two arguments: The first is the CTX object passed in by our handleRequest method, and the second, next, is actually a method passed in, which is the last function to process after all middleware is done. The core of this function is to recursively execute our Middleware. To understand this code, you need to understand itPromise.reslove().
Promise.reslove returns a Promise object of fulfillled
// Can be a shortcut to new Promise()

Promise.reslove(fn(context, dispatch.bind(null, i+1)));// Is actually equal to
new Promise((relove, reject) = > {
  reslove(fn(context, dispatch.bind(null, i+1)));
})
Copy the code
  1. Read this function carefully, it isWe define an index (using our closure to change the index one dispatch at a time)“, executes dispatch(0), which is the core of our implementation mechanism, and returns the middleware if it doesn’t get to the last middlewarePromise.reslove(fn(context, dispatch.bind(null, i + 1)))thefn(context, dispatch.bind(null, i + 1))That is, execute we passapp.useAdding the Middleware function,The Middleware function takes two arguments, context and next: the next middleware function, so that if one of the middleware in our KOA doesn’t execute next, any middleware added later won’t. And that’s what formed ourOnion ring model.
// Core method: recursively call our middlewares, based on Promise for asynchronous process control;
// promise.resolve () returns a thenable object;
// Therefore, the middleware in KOA2 is based on async functions and await the execution of the next middleware method;
return function (context, next) {
    // last called middleware #
    let index = - 1
    return dispatch(0)
    function dispatch (i) {
      if (i <= index) return Promise.reject(new Error('next() called multiple times'))
      index = i
      let fn = middleware[i]
      if (i === 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)
      }
    }
  }
Copy the code

Four,

  1. The Koa framework is small and elegant, and its source code is very small, just over a thousand lines. The execution mechanism of middleware is mainly to read the koa-compose code. Multiple middleware will form an advanced and out stack structure, and the current middleware controls the execution right of the next middleware.
  2. The function of Koa itself may not be able to meet the needs of our daily development. We can assist our development through many third-party packages or custom middleware. (Knowing the middleware mechanism, it is very easy to customize one)
  3. Koa1 manages our middleware with CO and Generator and Koa2 manages our middleware with async await (async functions return Promise objects).

Five, Koa2 actual combat

Koa2 – mysql-sequelize-jWT – koA2 – mysql-sequelize-jWT

Vi. Front-end Training Guide (I hope it can be helpful to you)

This is a personal blog (front-end training guide) : front-end-Web- Developer – Interview

Vi. Reference documents

  1. How long before Koa2 replaces Express
  2. Koa vs Express && Koa1 vs Koa2