/**
* 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 // 初始化index = -1, i = 0 , i > index
return dispatch(0)
function dispatch (i) {
// i比index大1
if (i <= index) return Promise.reject(new Error('next() called multiple times'))
index = i // index = 0、1、2、3、4、5...middleware.length
let fn = middleware[i] // fn = middleware[0]... fn=[middleware[middleware.length]] fn是一个async await异步函数
if (i === middleware.length) fn = next // ? next是undefined 最后一次遍历,说明中间件函数执行完了,返回 Promise.resolve()
if (!fn) return Promise.resolve()
try {
// Promise.resolve(middleware[0](context, dispatch.bind(null, i + 1)))
// middleware[0](context, dispatch(i + 1)) 1、2、3、4、5...middleware.length
// promise队列
return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
} catch (err) {
return Promise.reject(err)
}
}
}
}
koa-compose解析
于 2022-06-13 22:43:26 首次发布