直接上代码
// const add = (x, y) => x + y;
// const square = z => z * z
// // const compose = (fn1, fn2) => (...args) => fn2(fn1(...args))
// const compose = (...[first, ...other]) => (...args) => {
// let ret = first(...args)
// other.forEach(fn => {
// ret = fn(ret)
// console.log(ret)
// })
// return ret
// }
// // const fn = (x, y) => square(add(x, y))
// const fn = compose(add, square, square)
// console.log(fn(2, 3))
function compose(middlewares) {
return function() {
// 因为是异步函数,所以一定返回的是执行承诺
return dispatch(0) // 代表返回的是洋葱圈的最外层函数
// 代表middlewares数组中的第i个函数
function dispatch(i) {
// 取出对应的函数
let fn = middlewares[i]
if (!fn) {
// 如果不存在,返回一个空的执行承诺
return Promise.resolve()
}
return Promise.resolve(
// 执行function的时候是需要放参数的function fn1(next)
// next 其实就是某一个函数的执行承诺