koa2与express中间件机制的实现

 

// koa 中间件机制 koa1基于迭代器和生成器+prommsie(es6) koa2基于 async/await(es7)

class Koa {

constructor() {

this.middlewares = []

}

use(middleware) {

this.middlewares.push(middleware)

}

compose() {

return async () => {

function createNext(middleware, oldNext) {

return async function() {

await middleware(oldNext)

}

}

let len = this.middlewares.length

let next = async function() {

return Promise.resolve()

}

for (; len--;) {

next = createNext(this.middlewares[len], next)

}

await next()

}

}

}

let koa_app = new Koa()

koa_app.use(async (next) => {

console.log('m1')

await next()

})

koa_app.use(async (next) => {

console.log('m2')

await next()

})

koa_app.use(async (next) => {

console.log('m3')

await next()

})

let fn = koa_app.compose()

fn()

 

// express中间件机制 基于函数的回调 (es5)

function express() {

var funcs = []

var app = function() {

var i = 0

function next() {

var tesk = funcs[i++]

if (!tesk) {

return

}

tesk(next)

}

next()

}

app.use = function (task) {

funcs.push(task)

}

return app

}

var app = express()

app.use((next) => {

console.log('n1')

next()

})

app.use((next) => {

console.log('n2')

next()

})

app.use((next) => {

console.log('n3')

next()

})

app()

你可能感兴趣的:(jsvascript,框架)