1// 题目需求 2let middleware = [] 3middleware.push((next) => { 4 console.log(1) 5 next() 6 console.log(1.1) 7}) 8middleware.push((next) => { 9 console.log(2) 10 next() 11 console.log(2.1) 12}) 13middleware.push((next) => { 14 console.log(3) 15 next() 16 console.log(3.1) 17}) 18 19let fn = compose(middleware) 20fn() 21 22 23/* 241 252 263 273.1 282.1 291.1 30*/ 31 32//实现compose函数 33function compose(middlewares) { 34 35}
参考答案:
1/** 2 * Compose `middleware` returning 3 * a fully valid middleware comprised 4 * of all those which are passed. 5 * 6 * @param {Array} middleware 7 * @return {Function} 8 * @api public 9 */ 10function compose (middleware) { 11 // 校验传入的参数是数组,校验数组中每一项是函数 12 if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!') 13 for (const fn of middleware) { 14 if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!') 15 } 16 17 /** 18 * @param {Object} context 19 * @return {Promise} 20 * @api public 21 */ 22 23 return function (context, next) { 24 // last called middleware # 25 let index = -1 26 return dispatch(0) 27 function dispatch (i) { 28 // 一个函数中多次调用报错 29 // await next() 30 // await next() 31 if (i <= index) return Promise.reject(new Error('next() called multiple times')) 32 index = i 33 // 取出数组里的 fn1, fn2, fn3... 34 let fn = middleware[i] 35 // 最后 相等,next 为 undefined 36 if (i === middleware.length) fn = next 37 // 直接返回 Promise.resolve() 38 if (!fn) return Promise.resolve() 39 try { 40 return Promise.resolve(fn(context, dispatch.bind(null, i + 1))) 41 } catch (err) { 42 return Promise.reject(err) 43 } 44 } 45 } 46} 47 48
最近更新时间:2023-06-04