koa-compose 源码解析
Koa-Compose 函数解析
1 'use strict' 2 3 /** 4 * Expose compositor. 5 */ 6 7 module.exports = compose 8 9 /** 10 * Compose `middleware` returning 11 * a fully valid middleware comprised 12 * of all those which are passed. 13 * 14 * @param {Array} middleware 15 * @return {Function} 16 * @api public 17 */ 18 19 function compose (middleware) { 20 if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!') 21 for (const fn of middleware) { 22 if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!') 23 } 24 25 /** 26 * @param {Object} context 27 * @return {Promise} 28 * @api public 29 */ 30 31 return function (context, next) { 32 // last called middleware # 33 let index = -1 34 return dispatch(0) 35 function dispatch (i) {
// next 不允许调用多次 36 if (i <= index) return Promise.reject(new Error('next() called multiple times')) 37 index = i 38 let fn = middleware[i]
// fn 为最后一个表示没有其余中间件 next为最后一个 39 if (i === middleware.length) fn = next 40 if (!fn) return Promise.resolve() 41 try {
// 自增 42 return Promise.resolve(fn(context, dispatch.bind(null, i + 1))) 43 } catch (err) { 44 return Promise.reject(err) 45 } 46 } 47 } 48 }