https://github.com/koajs/comp.
// source link
//koa callback
const fn = compose(this.middleware);
fn(ctx).then(handleResponse).catch(onerror); //fncomposectxnextundefined
//compose
function compose (middleware) {
....
return function (context, next) { //next
// last called middleware -sharp
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//jsundefined nextundefined
if (!fn) return Promise.resolve()
try {
return Promise.resolve(fn(context, function next () {
return dispatch(i + 1)
}))
} catch (err) {
return Promise.reject(err)
}
}
}
}