readable.reduce(fn[, initial[, options]])


稳定性: 1 - 实验性

  • fn <Function> | <AsyncFunction> 一个用于对流中的每个数据块进行调用的归约函数。
    • previous <any> 从最后一次调用 fn 获得的值,或者如果指定了则为 initial 值,否则为流的第一个块。
    • data <any> 来自流的一段数据。
    • options <Object>
      • signal <AbortSignal> 如果流被销毁,则会中止,从而允许提前终止 fn 调用。
  • initial <any> 在归约中使用的初始值。
  • options <Object>
  • 返回:<Promise> 对减值最终金额的承诺。

此方法按顺序对流的每个块调用 fn,将前一个元素计算的结果传递给它。它返回一个表示归约最终值的 Promise。

🌐 This method calls fn on each chunk of the stream in order, passing it the result from the calculation on the previous element. It returns a promise for the final value of the reduction.

reducer 函数会逐元素迭代流,这意味着没有 concurrency 参数或并行处理。要并发执行 reduce,可以将其与 readable.map 方法链式调用。

🌐 The reducer function iterates the stream element-by-element which means that there is no concurrency parameter or parallelism. To perform a reduce concurrently, it can be chained to the readable.map method.

如果未提供 initial 值,则流的第一个数据块将用作初始值。如果流为空,Promise 将被拒绝,并返回一个 TypeError,其 code 属性为 ERR_INVALID_ARGS

🌐 If no initial value is supplied the first chunk of the stream is used as the initial value. If the stream is empty, the promise is rejected with a TypeError with the ERR_INVALID_ARGS code property.

import { Readable } from 'node:stream';

const ten = await Readable.from([1, 2, 3, 4]).reduce((previous, data) => {
  return previous + data;
});
console.log(ten); // 10