一个koa源码中的问题
发布于 8 年前 作者 lian774739140 4036 次浏览 来自 问答

koa2.0.0中,在application.js里有个callback函数

	callback() {
		const fn = compose(this.middleware);
		/*...*/
		return (req, res) => {
			/*...*/
			fn(ctx).then(() => respond(ctx)).catch(ctx.onerror);
		};
	}

其中用到了koa-compose的compose函数

	function compose(middleware){
		/*...*/
		return function (context, next) {
			let index = -1
			return dispatch(0)
			function dispatch(i) {
				if (i <= index) return Promise.reject(new Error('next() called multiple times'))
				index = i
				const fn = middleware[i] || next
				if (!fn) return Promise.resolve()
				try {
					return Promise.resolve(fn(context, function next() {
						return dispatch(i + 1)
					}))
				} catch(err) {
					return Promise.reject(err);
				}
			}
		}
	}

这个compose函数返回了一个有俩参数的函数(context和next),其中一个参数next在application.js的callback函数里是干啥用的呢?并没有使用到啊,百思不得其解。。。

6 回复

next 在这里是可缺省的,可以看做 (ctx, next = () => Promise.resolve()) => { ... }

具体来说,跟 if (!fn) return Promise.resolve() 这一行有关

@gyson 嗯,那看作 (ctx, next = undefined) 也可以是吧。。。问一下,在koa-compose的compose函数里,返回的函数去掉第二个参数(就是next),是不是完全没影响啊,在koa里?

compose 函数是接受多个 middleware,返回单个 middleware,所以返回的那个函数是 (ctx, next)

koa 的 callback 函数里确实没有用到这个 next

但是当你要组合的时候,就需要 next

比如 compose([mw, mw, compose([mw, mw]), mw])

@gyson 嗯嗯,谢谢~

可以给个koa的链接吗,github上找了半天没找到

回到顶部