项目作者: penghuwan

项目描述 :
compose是对处理函数集 functions 组合后的复合函数的统称,代码展示了三种不同的compose函数: 复合同步函数的compose,复合异步函数的composeAsync, 以及以类型Koa的洋葱圈的方式进行复合的onionCompose
高级语言: JavaScript
项目地址: git://github.com/penghuwan/compose-function-lib.git
创建时间: 2019-07-29T00:27:22Z
项目社区:https://github.com/penghuwan/compose-function-lib

开源协议:

下载


Compose Function

compose是对处理函数集 functions 组合后的复合函数的统称,下面展示了三种compose函数

  • compose: 复合同步函数
  • composeAsync: 复合异步函数
  • onionCompose: 以类型Koa的洋葱圈的方式进行复合

Example

compose

  1. function log1() {
  2. console.log("log1");
  3. return "log1"
  4. }
  5. function log2(str) {
  6. str += " log2";
  7. console.log(str);
  8. return str;
  9. }
  10. function log3(str) {
  11. str += " log3"
  12. console.log(str);
  13. }
  14. const composedFn = compose(log1, log2, log3);
  15. composedFn();

输出

  1. log1
  2. log1 log2
  3. log1 log2 log3

composeAsync

  1. async function log1() {
  2. console.log("log1");
  3. return "log1"
  4. }
  5. async function log2(str) {
  6. str += " log2";
  7. console.log(str);
  8. return str;
  9. }
  10. async function log3(str) {
  11. str += " log3"
  12. console.log(str);
  13. }
  14. const composedFn = composeAsync(log1, log2, log3);
  15. composedFn();

输出

  1. log1
  2. log1 log2
  3. log1 log2 log3

onionCompose

  1. async function log1(next) {
  2. console.log("log1 enter");
  3. await next();
  4. console.log("log1 out");
  5. }
  6. async function log2(next) {
  7. console.log("log2 enter");
  8. await next();
  9. console.log("log2 out");
  10. }
  11. async function log3(next) {
  12. console.log("log3 enter");
  13. await next();
  14. console.log("log3 out");
  15. }
  16. let onionFn = onionCompose(log1, log2, log3);
  17. onionFn();

输出

  1. log1 enter
  2. log2 enter
  3. log3 enter
  4. log3 out
  5. log2 out
  6. log1 out