One, koa2
koa2
,As follows:
express
Middleware is asynchronous callback, koa2
native supportasync/await
- New development frameworks and systems are beginning to be based on
koa2
, for exampleegg.js
express
Although not dated, but koa2
certainly is the future trend
async
And await
points:
await
Can be followed by promise
an object, acquires resolve
a value
await
You must be wrapped in async
a function inside
async
Also function executes a return of promise
objects
try-catch
Intercepted promise
in reject
value
koa2
The internal principle of middleware realization, the code is as follows:
const http = require('http')
function compose(middlewareList) {
return function (ctx) {
function dispatch(i) {
const fn = middlewareList[i]
try {
return Promise.resolve(fn(ctx, dispatch.bind(null, i + 1)))
} catch (err) {
return Promise.reject(err)
}
}
return dispatch(0)
}
}
class LikeKoa2 {
constructor () {
this.middlewareList = []
}
use (fn) {
this.middlewareList.push(fn)
return this
}
createContext (req, res) {
const ctx = {
req,
res
}
ctx.query = req.query
return ctx
}
handleRequest (ctx, fn) {
return fn(ctx)
}
callback () {
const fn = compose(this.middlewareList)
return (req, res) => {
const ctx = this.createContext(req, res)
return this.handleRequest(ctx, fn)
}
}
listen (...args) {
const server = http.createServer(this.callback())
server.listen(...args)
}
}
module.exports = LikeKoa2