koa带来了洋葱圈模型,这个模型可以用于koa(eggjs)的中间件.
axios可以利用洋葱圈模型实现拦截器,合并请求拦截器与响应拦截器。
ES6生成器
生成器是 ECMAScript 6 新增的一个极为灵活的结构,拥有在一个函数块内暂停和恢复代码执行的
能力。这种新能力具有深远的影响,比如,使用生成器可以自定义迭代器和实现协程。
— 节选自《JavaScript高级程序设计(第4版)》
洋葱圈的实现得益于生成器,下面是利用生成器实现的简易中间件
const stack = [ function (next) {
console.log(111)
next()
console.log(222)
}, function (next) {
console.log(333)
next()
console.log(444)
}, function (next) {
console.log(555)
next()
}]
function * compose() {
const callback = stack.shift()
while(callback) {
yield callback(() => compose().next())
}
}
compose().next()
/* console.log
111
333
555
444
222
*/
koa compose 中间件
'use strict'
/**
* Expose compositor.
*/
module.exports = compose
/**
* Compose `middleware` returning
* a fully valid middleware comprised
* of all those which are passed.
*
* @param {Array} middleware
* @return {Function}
* @api public
*/
function compose (middleware) {
if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')
for (const fn of middleware) {
if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')
}
/**
* @param {Object} context
* @return {Promise}
* @api public
*/
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)
}
}
}
}