compose函数

redux的compose学习

reduce 返回的是函数累计处理的结果
注意:此处使用的reduce,意味着reduce函数时按照从左往右包裹,所以最后执行的顺序是相反的,如果需要按照按照参数的顺序执行,就使用reduceRight

 function compose(...funcs) {
        if (funcs.length === 0) {
          return args => args;
        }
        if (funcs.length === 1) {
          return funcs[0];
        }
        return funcs.reduce(
          (a, b) =>
            (...args) =>
              a(b(...args))
        );
      }
function funca(params) {
        console.log(params, "funca");
        return "funca";
      }
      function funcnb(params) {
        console.log(params, "funcnb");
        return "funcnb";
      }
      function funcc(params) {
        console.log(params, "funcc");
        return "funcc";
      }
      compose(funca, funcnb, funcc)("参数")

效果:

compose 组合promise

function composePromise(...arg) {
        if (arg.length === 0) {
          return () => Promise.resolve();
        }
        if (arg.length === 1) {
          return arg[0];
        }
        return arg.reduceRight((a, b) => {
          return async (...args) => {
            return a(await b(...args));
          };
        });
      }
//测试
 let a = async (param) => {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            console.log("xhr1", param);
            resolve("xhr1");
          }, 5000);
        });
      };

      let b = async (param) => {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            console.log("xhr2", param);
            resolve("xhr2");
          }, 3000);
        });
      };
      let c = async (param) => {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            console.log("xhr3", param);
            resolve("xhr3");
          }, 3000);
        });
      };
 composePromise(
        a,
        b,
        c
      )(1).then((res) => {
        console.log(res, "res");
      });

效果如下:

redux源码地址:https://github.com/reduxjs/redux/blob/master/src/compose.ts

posted @ 2021-08-05 17:35  黑黑哈哈  阅读(206)  评论(0编辑  收藏  举报