【问题标题】:How can I represent the function chain using compose?如何使用 compose 表示函数链?
【发布时间】:2016-02-29 21:54:30
【问题描述】:

我正在使用highlandjs 库来读取文件并在其内容中添加结束卡,然后在控制台中显示它们:

const readFile = highland.wrapCallback(fs.readFile);
const addEndCard = x => x + '\nx---THE END---x\n';
files.map(readFile).parallel(3).map(addEndCard).each(console.log);

我想使用highland.compose 将它们包装到一个函数调用中,我开始使用:

const readAllFiles = highland.compose(
  highland.map,
  addEndCard,
  readFile
);
readAllFiles(files).parallel(3).each(console.log);

我得到错误:

TypeError: readAllFiles(...).parallel is not a function
    at Object.<anonymous> (/home/vamsi/Do/highland-fun/index.js:14:21)
    at Module._compile (module.js:398:26)
    at Object.Module._extensions..js (module.js:405:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Function.Module.runMain (module.js:430:10)
    at startup (node.js:141:18)
    at node.js:980:3

看起来组合函数没有返回highland stream

【问题讨论】:

    标签: node.js function-composition highland.js


    【解决方案1】:

    readFile 返回一个流,但 _.compose() 组合函数而不是流。

    我相信您正在寻找的是_.pipeline()

    【讨论】:

      【解决方案2】:

      您的组合函数没有返回流的原因是,通过传递map,就像您在那里所做的那样,您正在使用一个需要两个参数的柯里化函数。 compose 通过从右到左依次传递应用每个函数的结果来工作,即组合中的每个函数必须是一元的;当map 接收到单个参数时,它会返回一个期望最终参数而不是结果的函数,并且它会破坏下游的其余函数。像这样的东西应该可以工作:

      highland(files) // I presume files is an array
        .map(highland.compose(highland.map(addEndCard), readFile))
        .parallel(3)
        .each(console.log);
      

      另外,我可以维护您的原始 API 的唯一方法是这样的:

      const readAllFiles = highland.compose(
        highland.map(highland.map(addEndCard)),
        files => files.map(file => readFile(file))
      );
      
      readAllFiles(files).parallel(3).each(console.log);
      

      顺便说一句,您是否出于某种原因使用 parallel 而不是 merge?如果处理文件的顺序无关紧要,请使用merge

      【讨论】:

        猜你喜欢
        • 2023-01-31
        • 2020-07-29
        • 2021-10-23
        • 1970-01-01
        • 2014-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-25
        相关资源
        最近更新 更多